Check if Computer object exists in AD ?

I have a text file containing 100 server names. I would like to push these into a script and test wheather the computer object exists or if it has been decommissioned (deleted). From the results i can update a tracking sheet that has been left to the side for sometime.

Seems easy enough but i am having problems all day! Below is what i have so far..

Function check-server-object {

$serverlist = get-content "e:\serverlist.txt"
try
{
write-host "#################################"
write-host "Attempting to find computer"
write-host "#################################"

ForEach ($server in $serverlist){
#$tempVar = Get-ADComputer $server
if (Get-ADObject $server -eq $null) { Write-Host "not there"} else {Write-Host "$Server Found In AD!"}
}
}
catch {write-host "$server does not exist" -ForegroundColor Red}
}

check-server-object

I have the try & catch because i was having issues with errors etc.. little bit of a bodge. :/ any anyway so far it only gives me the result of the first server name in the text file... only another 99 to go!! why is it not giving me all the servers ?

Please can you help / explain on the logic and provide any solution to my problem.

 

Thanks,

Phil

Parents
  • Can I suggest a more PowerShell friendly style of output?

     

    ForEach ($server in (get-content "serverlist.txt")) 
    {   Try {
            Get-ADComputer $server -ErrorAction Stop
            $Result = $true
        }
        Catch {
            $Result = $False
        }
        [PSCustomObject]@{
            Name = $server
            Found = $Result
        }
    }

    What's nice about this output is it's in the form of a PowerShell object that can then be used anyway you want.  You could pipe it into Export-CSV for easy storage.  You could pipe the results of your script into Where-Object and create a new text file of just the good ones.  

    I think it's one of the key tenant's of PowerShell that if you stick with object output instead of text your code becomes reusable!  Now, maybe that's not really necessary in this case, I get it, but it's just something that you should always keep in mind :)

     

    Good luck!

  • How would you pipe this into an out-grid view. I've tried multiple ways and it either error out or creates multiple grid-views. Thank you,

Reply Children
No Data