PowerShell / PowerCli从Out-GridView传递Correct参数以删除快照

时间:2017-05-03 09:52:13

标签: powershell vmware powercli

我是PowerShell / PowerCLI的新手,现在我正在学习它的工作。我创建了一个简单的几行代码来列出所有快照,并使用out-gridview在另一个弹出窗口中列出它,选择一个或多个快照并单击“确定”将让我删除所选快照并且它可以正常工作

#List snapshot
$snapshot = Get-VM | Get-Snapshot | Out-GridView -Title "Snapshot Viewer" -OutputMode Multiple

#remove selected VM's snapshot
$snapshot | foreach { Remove-Snapshot $_ }

由于默认Get-Snapshot仅显示Snapshot Name,Description和PowerState,因此我添加了一个计数器,VM名称,以GB为单位的快照大小和快照的年龄。

$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 $_ }

现在$_似乎为Remove-Snapshot返回了错误的参数并收到错误:

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

感谢是否有人可以就如何解决此错误给我指导,传递正确的参数。

1 个答案:

答案 0 :(得分:1)

Select-Object将对象类型更改为PSCustomObject,但Remove-Snapshot似乎需要快照对象。

我无法访问vSphere系统,但如果您希望允许网格视图使用“增强信息”进行过滤,则可能需要先将快照存储在阵列中,然后从该阵列中获取所选快照删除。

这样的事可能有用:

$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]
}