Powershell:{_。Name不在$ object中}

时间:2012-05-22 08:24:25

标签: powershell filtering

我正在构建一个列出所有非活动计算机帐户的脚本。我想从结果中排除一些系统。

我有一个文本文件,其中包含要排除的所有系统(每行一个系统名称)。所有项目都存储在属性名称为“name”的对象中。所以$ excluded将包含:

name
----
system1
system2

要列出所有非活动系统,请使用Search-ADAccount cmdlet:

$InactiveComputers = Search-ADAccount -AccountInactive -TimeSpan 90 -ComputersOnly | Where {$_.Enabled -eq $true}

当然我可以逐个循环所有结果,但是有一种简单的方法可以直接从结果中排除系统吗?我有一种感觉,可以使用select-object或where-object,但我无法弄清楚如何与对象中的结果进行比较。

3 个答案:

答案 0 :(得分:15)

你在标题中使用它基本上是正确的:"其中{_.Name不在$ object}"

语法略有不同。将其传递给以下

Where { !($_.Name -in $excluded) }

OR

Where { $_.Name -notin $excluded }

两者似乎都在控制台中提供相同的结果。快乐的编码!

注意:在PSv2和v3上进行了测试。

我在寻找答案时遇到了这个问题,并且认为我会更新这些选项以适应其他人。

答案 1 :(得分:3)

导入排除文件(如csv)并使用-notcontains运算符:

$names = Import-csv exclude.txt | Foreach-Object {$_.Name} 

$InactiveComputers = Search-ADAccount -AccountInactive -TimeSpan 90 -ComputersOnly | Where {$_.Enabled -eq $true -and $names -notcontains $_.Name}

答案 2 :(得分:0)

我认为您可以使用-notcontainsTechNet article)运算符:

$InactiveComputers = Search-ADAccount -AccountInactive -TimeSpan 90 -ComputersOnly | Where {$_.Enabled -eq $true -and $excluded -notcontains $_.name }