In Powershell (well, PowerCLI), I am getting a list of virtual machines and just "get" the first of a sorted list
get-vm | where-object { $_.name -like "$vm-BkpClone-*"} | Sort-Object name | Select-Object -First 1
Now I need to call this at a later stage in an if-statement so I am trying to put this into a variable
$oldClone = get-vm | where-object { $_.name -like "$vm-BkpClone-*"} | Sort-Object name | Select-Object -First 1
It
kinda works, but not perfectly. I noticed whilst it seems to be working, it breaks other parts of the script, writing to a logfile for example.
Here the whole extract from the part in question
If(Get-VM $cloneName)
{
"$(Get-Date –f o) - $cloneName Created Sucessfully" | Out-File $VM_Clonelog -Append -Encoding "ASCII"
$oldClone = get-vm | where-object { $_.name -like "$vm-BkpClone-*"} | Sort-Object name | Select-Object -First 1
if ($oldClone -match $cloneName)
{
Write-Host "`nCreated clone is the only copy - nothing to delete" | Out-File $VM_Clonelog -Append -Encoding "ASCII"
}
else
{
Write-Host "`nDeleting oldest clone" | Out-File $VM_Clonelog -Append -Encoding "ASCII"
Get-VM $oldClone | Remove-VM -DeleteFromDisk -Confirm:$False | Out-File $VM_Clonelog -Append -Encoding "ASCII"
}
$VMsCloned = $VMsCloned +1
}
The second line "$cloneName Created Sucessfully" is being passed correctly into the logfile, and from that point on it stops.
I also notice that if I am moving
$oldClone = get-vm | where-object { $_.name -like "$vm-BkpClone-*"} | Sort-Object name | Select-Object -First 1
Outside the "main" if-statement, the second if-statement stops working.
Hope it make sense ?