Reputation: 53
I'm trying to grab a list of all the computer names on my network and see if a directory exists on that PC in powershell, but I am having problems. Can someone look this over and tell me what I'm doing wrong?
$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
}
Upvotes: 0
Views: 1055
Reputation: 174485
By default dsquery computer
only returns the DistinguishedName for each computer, like so:
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"
So, your -path
argument becomes:
"\\CN=Computer01,ou=TESTOU,dc=example,dc=com.\C$\Program Files (x86)\Bit9\Parity Agent"
Which is no good.
Use dsquery * "ou=TESTOU,dc=example,dc=com" -attr Name
to get the computers name instead, and parse it using 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
Upvotes: 1