@cs-user-0db1952cb89b Welcome to Microsoft Q&A, Thank you for posting your here!!
Make sure to set the VM configuration object in $VirtualMachine first then set the operating system
Create the VM configuration object
$VmName = "VirtualMachinelatest"
$VmSize = "Standard_A1"
$VirtualMachine = New-AzVMConfig -VMName $VmName -VMSize $VmSize
$VirtualMachine = Set-AzVMOperatingSystem -VM $VirtualMachine -Windows -ComputerName "MainComputer" -Credential $Credential -ProvisionVMAgent
$VirtualMachine = Set-AzVMSourceImage -VM $VirtualMachine -PublisherName "MicrosoftWindowsServer" -Offer "WindowsServer" -Skus "2016-Datacenter" -Version "latest"
For complete script please check the document here
Hope this helps!
Kindly let us know if the above helps or you need further assistance on this issue.
-------------------------------------------------------------------------------------------------------------------
Please do not forget to "Accept the answer” and “up-vote” wherever the information provided helps you, this can be beneficial to other community members.