Hi everyone,
I got this fuction from LucD in another forum post and modified it to attempt to convert a large number of VMs from thick to thin disks. I seem to be getting an error on the first VM every time and the second seems to be working fine. If someone could point out what I've done wrong I would appreciate it.
Error:
You cannot call a method on a null-valued expression.
At C:\Users\xxx\Documents\xxx.ps1:33 char:31
+ $vmView.RelocateVM <<<< ($spec, $null)
+ CategoryInfo : InvalidOperation: (RelocateVM:String) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
Script:
$vmarray = @("TestVM1","TestVM2")
$datastore = Get-Datastore | Sort FreeSpaceMB -Descending
function Move-VMThin {
PARAM(
[Parameter(Mandatory=$true,ValueFromPipeline=$true,HelpMessage="Virtual Machine Objects to Migrate")]
[ValidateNotNullOrEmpty()]
[System.String]$VM
,[Parameter(Mandatory=$true,HelpMessage="Destination Datastore")]
[ValidateNotNullOrEmpty()]
[System.String]$Datastore
)
Begin {
#Nothing Necessary to process
} #Begin
Process {
#Prepare Migration info, uses .NET API to specify a transformation to thin disk
$vmView = Get-View -ViewType VirtualMachine -Filter @{"Name" = "$VM"}
$dsView = Get-View -ViewType Datastore -Filter @{"Name" = "$Datastore"}
#Abort Migration if free space on destination datastore is less than 50GB
if (($dsView.info.freespace / 1GB) -lt 50) {throw "Move-ThinVM ERROR: Destination Datastore $Datastore has less than 50GB of free space. This script requires at least 50GB of free space for safety. Please free up space or use the VMWare Client to perform this Migration"}
#Prepare VM Relocation Specificatoin
$spec = New-Object VMware.Vim.VirtualMachineRelocateSpec
$spec.datastore = $dsView.MoRef
$spec.transform = "sparse"
#Perform Migration
$vmView.RelocateVM($spec, $null)
} #Process
}
for ($i=0; $i -lt $vmarray.count; $i++)
{
$datastore
$snapshot = Get-VM -Name $vmarray[$i] | Get-Snapshot
if ($snapshot -eq $null)
{
$vmds = Get-VM -Name $vmarray[$i] | Get-Datastore
if ($vmds -ne $datastore[0])
{
Move-VMThin -VM $vmarray[$i] -Datastore $datastore[0]
}
if ($vmds -eq $datastore[0])
{
Move-VMThin -VM $vmarray[$i] -Datastore $datastore[1]
}
}
if ($snapshot -ne $null)
{
Write-Host $vmarray[$i]+"has a Snapshot" -ForegroundColor Red
}
}