Reputation: 23
I am a PowerShell/PowerCLI newbie, now I'm learning it for work. I've created a simple few lines code to list all snapshots and use the out-gridview to list it in another popup window, selecting one or multiple snapshots and click on "Ok" will let me delete the selected snapshot and it worked without issue.
#List snapshot
$snapshot = Get-VM | Get-Snapshot | Out-GridView -Title "Snapshot Viewer" -OutputMode Multiple
#remove selected VM's snapshot
$snapshot | foreach { Remove-Snapshot $_ }
Because default Get-Snapshot
only displays Snapshot Name, Description, and PowerState, I added a counter, VM Name, Snapshot Size in GB and age of the snapshot.
$counter = 1
#List snapshot with more information
$snapshot = Get-VM | Get-Snapshot |
Select-Object @{Name="ID";Expression={$global:counter;$global:counter++}},
VM, Name, @{Name="SizeGB";Expression={[math]::Round($_.sizeGB,2)}},
@{Name="Days";Expression={(New-TimeSpan -End (Get-Date) -Start $_.Created).Days}} |
Out-GridView -Title "Snapshot Viewer" -OutputMode Multiple
#remove selected VM's snapshot
$snapshot | foreach { Remove-Snapshot $_ }
And now the $_
seems to return the wrong parameter for Remove-Snapshot
and get an error:
Remove-Snapshot : Cannot bind parameter 'Snapshot'. Cannot convert the "@{ID=4; VM=Win7-Golden; Name=SS20170227 v3.1; SizeGB=0.00; Days=64}" value of type "Selected.VMware.VimAutomation.ViCore.Impl.V1.VM.SnapshotImpl" to type "VMware.VimAutomation.ViCore.Types.V1.VM.Snapshot". At D:\powershell\snapshot_with_index.ps1:10 char:39 + $snapshot | foreach { Remove-Snapshot $_ } + ~~ + CategoryInfo : InvalidArgument: (:) [Remove-Snapshot], ParameterBindingException + FullyQualifiedErrorId : CannotConvertArgumentNoMessage,VMware.VimAutomation.ViCore.Cmdlets.Commands.RemoveSnapshot
Appreciate if anyone can give me guidance on how to solve this error, to pass the correct parameter.
Upvotes: 2
Views: 785
Reputation: 200293
Select-Object
changes the object type to PSCustomObject
, but Remove-Snapshot
seems to expect a snapshot object.
I don't have access to a vSphere system, but if you want to allow filtering by a gridview with "enhanced information" you probably need to store the snapshots in an array first, and then get the selected snapshots from that array for deletion.
Something like this might work:
$snapshots = @(Get-VM | Get-Snapshot)
0..($snapshots.Count - 1) | ForEach-Object {
$i = $_
$snapshots[$i] | Select-Object @{n='ID';e={$i}}, ...
} | Out-GridView -Title "Snapshot Viewer" -OutputMode Multiple | ForEach-Object {
Remove-Snapshot $snapshots[$_.ID]
}
Upvotes: 2