Powershell - 在使用 get-adcomputer 时过滤 OU [英] Powershell - Filtering OUs while using get-adcomputer
问题描述
我正在尝试创建一个脚本,该脚本根据计算机可能具有的特定属性生成计算机列表.例如,我正在尝试列出 Windows XP 计算机和 Windows 7 计算机,将它们的名称放入 .csv 文件中并输出每个的最终计数.
I am trying to create a script that generates a list of computers based on specific properties which a computer may have. For example, I am trying to make a list of Windows XP computers and Windows 7 computers, throw their names in a .csv file and outputting the final count of each.
这是我目前的代码
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:usersadmindesktop est.txt
}
elseif ($computer.OperatingSystem -like "Windows XP*") {
$j++
'"{0}","{1}","{2}"' -f $computer.Name, $computer.OperatingSystem, "$computer.DistinguishedName" | Out-file -append C:usersadmindesktop est.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 来使它更好一些,但我无法弄清楚.
This script works however I would like to make it a bit better by being able to say which OU's not to look into, but I can't quite figure it out.
如果有人对如何执行此操作有任何见解,甚至只是为了使上述代码更好,我很乐意听到.
If anyone has any insight into how to do this, or even just to make the above code any better I would love to hear it.
谢谢!
推荐答案
-like
运算符似乎不适用于 DistinguishedName 的通配符.所以明显的操作 Get-ADComputer -Filter {(DistinguishedName -notlike "*OU=evil,*")}
不起作用.
The -like
operator doesn't seem to work with wildcards for DistinguishedName. So the obvious operation Get-ADComputer -Filter {(DistinguishedName -notlike "*OU=evil,*")}
doesn't work.
最简单的解决方法是将所有计算机收集到一个集合中,然后对其进行过滤以满足您的需要.像这样,
The easiest workaround is to get all the computers in a colleciton and filter it afterwards to suit your needs. Like so,
# 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)
To combine matching rules, use -and
-or
and -like
. Remember to use *
wildcard with ? (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 - 在使用 get-adcomputer 时过滤 OU的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!