在 PowerShell 中将 Where-Object 与对象一起使用

Using Where-Object with an object in PowerShell

我似乎无法理解某些事情,我希望有人能提供帮助

我有一个名为 $SnapVMsAll 的对象数组,如下所示:

VMName                    Name                                             SnapshotType CreationTime        ParentSnapshotName
------                    ----                                             ---------- ------------        ------------------
SHARED-server.host.com    SHARED-server.host.com - (02/10/2017 - 13:02:44) Standard     02/10/2017 13:05:58       

我需要显示此对象数组中名称列中具有字符串 "Veeam" 的所有记录,但我认为我在隔离要比较的对象的特定属性时遇到了问题。

我的尝试如下:

echo $SnapVMsAll | Where-Object (Foreach-Object -MemberName name) -Like "Veeam Replica"

这返回了错误:

Where-Object : Cannot validate argument on parameter 'Property'. The argument is null or empty. Provide an argument that is not null or empty, and then try the command again.

我也试过了

echo $SnapVMsAll | Where-Object $SnapVMsAll.name -Like "Veeam Replica"

但我又遇到同样的错误。

$SnapVMsAll不存在于管道内部,它是你传递给管道的对象。在管道中,可以使用自动变量 $_.

访问对象

另请注意,-Like 通常与通配符一起使用以匹配字符串。如果名字是Veeam Replica你应该使用-eq,如果名字包含Veeam Replica,你应该改成-Like "*Veeam Replica*"

因此,将您的代码更改为以下内容应该可行:

$SnapVMsAll | Where-Object { $_.name -Like "*Veeam Replica*" }