PowerShell: Add New Virtual Disk to Existing Guest VM in Hyper-V

# Adding disks (optional)
$newVMNames='TestWindows2019'
$extraDiskSize='200GB'

if($extraDiskSize){
    foreach($newVmName in $newVMNames){
        STOP-VM -vmname $newVmName
        $diskFile=(join-path $destinationFolder $newVmName) + "\$newVmName`_disk1.vhdx"
        NEW-VHD -Fixed $diskFile -SizeBytes (Invoke-Expression $extraDiskSize) -ea Stop
        # Preempt error by adding (Invoke-Expression $sizeBytes)
        # New-VHD : Cannot bind parameter 'SizeBytes'. Cannot convert value "200GB" to type "System.UInt64". Error: "Input
        # string was not in a correct format."
        # At line:1 char:45
        # +         NEW-VHD -Fixed $diskFile -SizeBytes $extraDiskSize -ea Stop
        # +                                             ~~~~~~~~~~~~~~
        #     + CategoryInfo          : InvalidArgument: (:) [New-VHD], ParameterBindingException
        #     + FullyQualifiedErrorId : CannotConvertArgumentNoMessage,Microsoft.Vhd.PowerShell.Cmdlets.NewVhd
        Add-VMHardDiskDrive -VMName $newVmName -Path $diskFile
    }
}

Leave a Reply

Your email address will not be published. Required fields are marked *