我正在尝试获取网络上所有计算机名称的列表,并查看PowerShell中该PC上是否存在目录,但是我遇到了问题。有人能看一遍并告诉我我做错了吗?
$computers = dsquery computer "ou=TESTOU, dc=example, dc=com"
foreach($computer in $computers) {
If(!(Test-Path -path "\\$computer.\C$\Program Files (x86)\Bit9\Parity Agent")) {
Write-Host $computer
}
Out-File -FilePath .\result.txt
}
答案 0 :(得分:1)
默认情况下,dsquery computer
仅返回每台计算机的 DistinguishedName ,如下所示:
C:\>dsquery computer "ou=TESTOU,dc=example,dc=com"
"CN=Computer01,ou=TESTOU,dc=example,dc=com"
"CN=Computer02,ou=TESTOU,dc=example,dc=com"
"CN=Computer03,ou=TESTOU,dc=example,dc=com"
"CN=Computer04,ou=TESTOU,dc=example,dc=com"
因此,您的-path
参数变为:
"\\CN=Computer01,ou=TESTOU,dc=example,dc=com.\C$\Program Files (x86)\Bit9\Parity Agent"
哪个不好。
使用dsquery * "ou=TESTOU,dc=example,dc=com" -attr Name
代替获取计算机名称,并使用ConvertFrom-Csv
解析它:
# Retrieve computer names
$Computers = dsquery * "ou=TESTOU,dc=example,dc=com" -filter "(objectClass=computer)" -attr Name -limit 0 | ConvertFrom-Csv -Delimiter " "
# Select only the name from the output
$Computers = $Computers | Select-Object -ExpandProperty Name
# Assign any output from the foreach loop to $Results
$Results = foreach($Computer in $computers){
$Path = '\\{0}\C$\Program Files (x86)\Bit9\Parity Agent' -f $Computer
if(!(Test-Path -Path $Path)){
# Don't use Write-Host, it only write text to the console
$Computer
}
}
# Write the computer names that failed to .\result.txt
$Results | Out-File -FilePath .\results.txt