Im trying to accomplish the above with the script below:
Connect-VIServer -Server ServerName01
$VMName = Get-VM | Get-Snapshot |
Where {$_.Created -lt (Get-Date).AddDays(-30)} | select VM |
ForEach-Object {
$VMName.ExtensionData.ConsolidateVMDisks()
}
Im quite new to PowerCLI and this is the best ive come up with so far.
I dont want to run this comand until I can see the contents of the variable $VMName so I ran the following command.
Get-VM | Get-Snapshot | Where {$_.Created -lt (Get-Date).AddDays(-30)} | select VM
Which does return a list of VMNames that meet the above criteria (manual check confirms)
The initial code does not work, it doesnt pass anything at all in the $VMName variable to ExtensionData.ConsolidateVMDisks()
Get-VM | Get-Snapshot | Where-Object {$_.Created -lt (Get-Date).AddDays(-30)} | Remove-Snapshot
works but i would like to see the name of the VM and the Snapshot in the confirmation window.
Thanks.
The following will allow you to execute the ConsolidateVMDisks()
method for each VM.
$VMName = Get-VM | Get-Snapshot |
Where {$_.Created -lt (Get-Date).AddDays(-30)} | select VM
$VMName | Foreach-Object {
$_.VM.Name
$_.VM.ExtensionData.ConsolidateVMDisks()
}
The following will meet your requirements using the Remove-Snapshot
command:
$Snapshots = Get-VM | Get-Snapshot | Where-Object {$_.Created -lt (Get-Date).AddDays(-30)}
$Snapshots | Foreach-Object {
"VM Name: {0}" -f $_.VM.Name
"Snapshot Name: {0}" -f $_.Name
$_ | Remove-Snapshot
}
In your initial attempt, $VMName
contains an array of VM objects. When you pipe an array into a Foreach-Object
script block, the current object becomes $_
or $PSItem
. That current object is where you must access the property and corresponding methods. I added the $_.Name
code to display the current VM name to the console before the consolidate happens. Feel free to remove it if the method already provides the output you need.