2
votes

I'm just beginning to dip into PowerShell with AD so I apologize if the question seems obvious.

I am trying to check if which of the devices provided in a list are in AD. So far I've used the code from: Powershell - verify object exists in AD

It works just fine, but the "-ErrorAction SilentlyContinue" does not actually suppress the error messages. I get the below:


Get-ADComputer : Cannot find an object with identity: 'test' under:
'DC=test,DC=dom'.
At C:\Users\testaccount\Desktop\test.ps1:171
char:19
+ if (@(Get-ADComputer $target -ErrorAction SilentlyContinue).Count)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (test:ADComputer) [Get-ADComputer], ADIdentityNotFoundException
+ FullyQualifiedErrorId : ActiveDirectoryCmdlet:Microsoft.ActiveDirectory.Management.ADIdentityNotFoundException,Microsoft.ActiveDirectory.Management.Commands.GetADComputer


The code I am using is as follows:

foreach ($target in $devicelist)
{
    if (@(Get-ADComputer $target -ErrorAction SilentlyContinue).Count)
    {
        $existingdevices += $target
    }
    else
    {
        #display error notification
    }
}

What I am looking for is suppressing the error message to no longer show in console - for the script to actually silently continue on error.

Any and all help will be appreciated!

2
use the try/catch version shown in that link with the -ErrorAction set to Stop.Lee_Dailey
@Lee_Dailey Thanks! That did help, but I was wondering why it wouldn't with the if/else -erroraction setup?UncleJosephS
i don't know. [blush] i don't have access to the AD cmdlets ... but they are notorious for not doing what a proper PoSh cmdlet should do. ///// besides, the try/catch version is more standard, more controlled, AND easier to understand if one is familiar with the structure.Lee_Dailey

2 Answers

3
votes

So lets talk about whats happening.

There are 2 types of errors Terminating and Non-Terminating.

Terminating stops the execution of a command and throws an Exception. A non-terminating returns a write-out error message.

-ErrorAction takes care of Non-Terminating errors

Try{}Catch{} takes care of Terminating errors.

In your case

foreach ($target in $devicelist)
{
    try{
        if (@(Get-ADComputer $target -ErrorAction SilentlyContinue).Count)
        {
            $existingdevices += $target
        }
        else
        {
            #display non-terminating error notification
        }
    }catch{
        #display Terminating error notification
    }
}
0
votes

Use output redirection: 2> $Null

Get-ADComputer -Server BlahBlah -Identity ComputerThatDoesntExist 2> $Null