$vmName='TestVm'
$storageLocation='\\FILESERVER06\SHAREXOXO'
$newDiskSize='100GB'
$dynamic=$true
function createNewDisk{
    param(
        $vmName,
        $storageLocation,
        $newDiskSize='100GB',
        $dynamic=$true
        )
    $ErrorActionPreference='stop'

    try{
        write-host "Performing discoveries on $env:computername..."
        $vmObject=Get-VM -VMName $vmname
        $vmObject|Update-ClusterVirtualMachineConfiguration
        $currentHost=$vmObject.ComputerName
        $diskController=$vmObject | get-vmharddiskdrive
        $availableSlot=$diskController|sort -Descending -Property ControllerLocation| select -first 1 | `
                        Select-Object ControllerType,ControllerNumber,@{name='nextLocation';e={$_.ControllerLocation+1}}
        $newDiskLocation="$storageLocation\$vmName`_disk_$($availableSlot.nextLocation).vhdx"
    
        # Sanity check: avoid UNC path issues inside Remote PowerShell sessions
        $isUncPath=([System.Uri]$newDiskLocation).IsUnc
        $localSession=(get-host).Name -eq 'ConsoleHost' # WinRM session would yield 'ServerRemoteHost'
        if($isUncPath -and !$localSession){
            write-warning "UNC path is detected! This function must be executed on the parent host: $currentHost"
            return $false
        }

        # Create the vhdx file
        $fileExists=test-path $newDiskLocation
        try{
            if(!$fileExists){
                $command="New-VHD -Path $newDiskLocation -SizeBytes $($newDiskSize/1) $(if($dynamic){'-Dynamic'}else{'-fixed'})"
                write-host $command
                pause
                Invoke-Expression $command
                }
        }catch{
            
            }
    
        # Attach the virtual disk
        $controllerType=$availableSlot.ControllerType
        $controllerNumber=$availableSlot.ControllerNumber
        $slotNumber=$availableSlot.nextLocation
        $command="Add-VMHardDiskDrive -VMName $vmName -Path $newDiskLocation -ControllerType $controllerType -ControllerNumber $controllerNumber -ControllerLocation $slotNumber"
        #$command="Add-VMHardDiskDrive -VMName $vmName -Path $newDiskLocation"
        write-host $command
        pause
        Invoke-Expression $command
        return $true
    }catch{
        Write-Warning $error[0].Exception.Message
        $revertCommand="Remove-VMHardDiskDrive -VMName $vmName -ControllerType $controllerType -ControllerNumber $controllerNumber -ControllerLocation $slotNumber"
        write-host $revertCommand
        $vmObject|Update-ClusterVirtualMachineConfiguration
        pause
        Invoke-Expression $revertCommand
        return $false
        }
}

createNewDisk $vmName $storageLocation $newDiskSize $dynamic
# Troubleshooting:
# Error:
#Add-VMHardDiskDrive : Rolling back the results of an unsuccessful operation has failed.
#At line:1 char:1
#+ Add-VMHardDiskDrive -VMName TEST-SERVER.kimconnect.com -Path \\ ...
#+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#    + CategoryInfo          : NotSpecified: (:) [Add-VMHardDiskDrive], VirtualizationException
#    + FullyQualifiedErrorId : OperationFailed,Microsoft.HyperV.PowerShell.Commands.AddVMHardDiskDrive
#
#Add-VMHardDiskDrive : Failed to add device 'Virtual Hard Disk'.
#'TEST-SERVER.kimconnect.com' failed to add device 'Virtual Hard Disk'. (Virtual machine ID)
#At line:1 char:1
#+ Add-VMHardDiskDrive -VMName TEST-SERVER.kimconnect.com -Path \\ ...
#+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#    + CategoryInfo          : NotSpecified: (:) [Add-VMHardDiskDrive], VirtualizationException
#    + FullyQualifiedErrorId : OperationFailed,Microsoft.HyperV.PowerShell.Commands.AddVMHardDiskDrive
#
# Resolution:
# Shutdown the VM prior to attaching SCSI disks
# stop-vm $vmname
# createNewDisk $vmName $storageLocation $newDiskSize $dynamic
# start-vm $vmname
# Exception:
#WARNING: There were issues updating the virtual machine configuration that may prevent the virtual machine from
#running. For more information view the report file below.
#WARNING: Report file location: C:\Windows\cluster\Reports\Update-ClusterVirtualMachineConfiguration '' on 2012.08.06 At
# 15.06.htm
# The path where the virtual machine hard disk is stored, '\\UNCPATH\SHARE05\TESTSERVER.vhdx', 
# is not on storage managed by this failover cluster. Verify that the path is accessible from all nodes of the cluster that can own this virtual machine.

#PS C:\Windows\system32> get-vm $vmname|Set-VMProcessor -CompatibilityForMigrationEnabled 1
#Set-VMProcessor : Failed to modify device 'Processor'.
#Cannot change the processor settings of a virtual machine now.
#'TestVM' failed to modify device 'Processor'. (Virtual machine ID)
#
#Cannot change the processor settings of virtual machine 'TestVM' while it is in a saved state.
#(Virtual machine ID )
#At line:1 char:16
#+ get-vm $vmname|Set-VMProcessor -CompatibilityForMigrationEnabled 1
#+                ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#    + CategoryInfo          : InvalidOperation: (:) [Set-VMProcessor], VirtualizationException
#    + FullyQualifiedErrorId : InvalidState,Microsoft.HyperV.PowerShell.Commands.SetVMProcessor

#PS C:\Windows\system32> Remove-VMSavedState $vmname
#Remove-VMSavedState : The operation cannot be performed while the virtual machine is in its current state.
#At line:1 char:1
#+ Remove-VMSavedState $vmname
#+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~
#    + CategoryInfo          : InvalidOperation: (VirtualMachine ...-53ec99d5257b']:VirtualMachine) [Remove-VMSavedStat
#   e], VirtualizationException
#    + FullyQualifiedErrorId : InvalidState,Microsoft.HyperV.PowerShell.Commands.RemoveVMSavedState