smi*_*iel 6 powershell filtering active-directory ou
我正在尝试创建一个脚本,根据计算机可能具有的特定属性生成计算机列表.例如,我正在尝试制作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"
Run Code Online (Sandbox Code Playgroud)
样本输出:
104 Win 7
86 Win xp
190 Total
Run Code Online (Sandbox Code Playgroud)
这个脚本有效,但是我想通过能够说出哪些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,*"}
Run Code Online (Sandbox Code Playgroud)
附录
要组合匹配规则,请使用-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,*"
Run Code Online (Sandbox Code Playgroud)
}
| 归档时间: |
|
| 查看次数: |
36720 次 |
| 最近记录: |