powershell - Powershell-使用get-adcomputer时过滤OU

标签 powershell active-directory filtering 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"

样本输出:
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/

相关文章:

ruby - 支持 ObjectGUID 的 Ruby Active Directory gem

shell - 尾-f | sed 到文件不起作用

Powershell:并行运行多个作业并查看来自后台作业的流式传输结果

powershell - 如何在 Powershell 中自动检查 Telnet 端口?`

azure - 用于检查 Azure Cosmos 中是否启用自动缩放的 PowerShell 脚本

powershell - 如何使用 PowerShell 从远程计算机获取所有(IIS)网站状态/状态?

ASP.NET成员资格-使用哪个RoleProvider以便User.IsInRole()检查ActiveDirectory组?

powershell - 如何使 Windows DNS 和 WINS 设置保留在 Azure VM 中?

arrays - Swift - 获取数组中的第一项,并返回元素和索引

java - 如何用Java实现过滤迭代器?