我正在尝试创建一个脚本,该脚本根据计算机可能具有的特定属性来生成计算机列表。例如,我试图列出Windows XP计算机和Windows 7计算机,将它们的名称放入.csv文件中,并输出它们的最终计数。
到目前为止,这是我的代码
import-module ActiveDirectory
$computers = get-adcomputer -Filter 'ObjectClass -eq "Computer"' -properties "OperatingSystem"
$i = 0
$j = 0
Foreach ($computer in $computers) {
if ($computer.operatingSystem -like "Windows 7*") {
$i++
'"{0}","{1}","{2}"' -f $computer.Name, $computer.OperatingSystem, "$computer.DistinguishedName" | Out-file -append C:\users\admin\desktop\test.txt
}
elseif ($computer.OperatingSystem -like "Windows XP*") {
$j++
'"{0}","{1}","{2}"' -f $computer.Name, $computer.OperatingSystem, "$computer.DistinguishedName" | Out-file -append C:\users\admin\desktop\test.txt
}
else {
$_
}
}
write-host "$i Win 7"
write-host "$j Win xp"
$k = $i+$j
write-host "$k Total"
样本输出:
104 Win 7
86 Win xp
190 Total
该脚本有效,但是我想通过说出不应该研究哪个OU来使它更好一些,但是我不太清楚。
如果有人对如何执行此操作有任何见识,或者甚至只是想使上述代码变得更好,我将很乐意听到。
谢谢!
最佳答案
-like
运算符似乎不适用于DistinguishedName的通配符。因此,明显的操作Get-ADComputer -Filter {(DistinguishedName -notlike "*OU=evil,*")}
不起作用。
最简单的解决方法是将所有计算机都放入一个计算机中,然后对其进行过滤以适应您的需求。像这样
# All the computers from the evil OU:
$evilOU = $computers| ? {$_.DistinguishedName -like "*ou=evil,*"}
# All the computers but the ones from the evil OU:
$goodOU = $computers| ? {$_.DistinguishedName -notlike "*ou=evil,*"}
附录
要组合匹配规则,请使用
-and
-or
和-like
。请记住将*
通配符与? (where-object)
一起使用# All the computers save the ones from evil and wicked OU:
$goodOU = $computers| ? {
$_.DistinguishedName -notlike "*ou=evil,*" -and $_.DistinguishedName -notlike "*ou=wicked,*"
}
关于powershell - Powershell-使用get-adcomputer时过滤OU,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11531694/