Hello @bandolton ,
Thanks for reaching out to Microsoft Q&A.
Let me explain you those 2 lines where $VM was defined twice:
$vm = Get-AzVM -name $machinename -resourcegroupname $resourcegroup
Above command is fetching the details of the existing Virtual Machine , once that command runs $vm variable will have all the details about the VM
More precisely , if you do $vm.StorageProfile.DataDisks , after that command - if there are no data disks - it will show empty.
Now coming to next command:
$vm = add-azvmdatadisk -vm $vm -name $name -createoption attach -ManagedDiskId $datadisk01.id -lun 1
It is trying to add the data disk to the VM whose reference details are there in $VM after adding the data disk the same variable is being overridden.
In this case, after running the above command if you see the output of $vm.StorageProfile.DataDisks - you will see the output as something like below:
Name : disk1
DiskSizeGB :
Lun : 1
Caching : None
CreateOption : attach
SourceImage :
VirtualHardDisk :
Basically $VM is considered as an object pointing to some class which has multiple attributes .
When the second command gets executed : $vm = add-azvmdatadisk -vm $vm -name $name -createoption attach -ManagedDiskId $datadisk01.id -lun 1
Only a part of the attribute i.e. disk related is being modified and others are unchanged.
So what it means is , when we use the same variable $vm - only additional required attributes are being updated others are not changed. (like all other VM properties).
Now when we do update-azvm - It will update the VM with the latest changed parameters
Obviously we can also use some other variable with name $vm1 , it should be okay. By reusing the same variable sometimes we will be saving memory (Ofcourse in this case as it is a simple script it does not make any difference)
Hope that explanation helps you out in understanding better. Our best wishes are with you for your AZ104 exam.
Kindly let us know if you have additional questions !
Also make sure to "upvote and Accept the answer" if that helps out in answering your doubts
Regards,
Shiva.