3

I have a problem checking if a computer object exists in AD or not. To be specific it should go into an "else" if not.

This is my code:

if (Get-ADComputer "$Computer") {
        Get-ADComputer $Computer | Set-ADComputer -Enabled $false
        Start-Sleep -s 2 
        Get-ADComputer $Computer | Move-ADObject -TargetPath $PathOU
        Start-Sleep -s 2 
} else {
    write-host "Example"
}

When the input computer doesn't exist, the problem is, the command Get-ADComputer "$Computer" already fails in the if statement, so it never reaches the else.

How can I avoid that?

Thanks in advance.

2 Answers 2

1

Use Try Catch instead:

try {
    Get-ADComputer $Computer | Set-ADComputer -Enabled $false
    Start-Sleep -s 2 
    Get-ADComputer $Computer | Move-ADObject -TargetPath $PathOU
    Start-Sleep -s 2 
catch {
    Write-Host "Example"
}
Sign up to request clarification or add additional context in comments.

2 Comments

this may not always work; you should add to the cmdlet -ErrorAction Stop
@Avshalom Not really in this case. AD Cmdlets produce pipeline terminating errors always
1

Add the Get-ADComputer to a variable before the if block to help. Also before setting that variable with the command, set it to null per the below example. In addition to that, change up the if block to first check if it does not exist and to run that logic first then else run logic if it does exist.

$comp = "";
$comp = Try {Get-ADComputer "$Computer"} Catch {$false};

if (!$comp) {
    write-host "Example"
    } else {
        $comp | Set-ADComputer -Enabled $false
        Start-Sleep -s 2 
        $comp | Move-ADObject -TargetPath $PathOU
        Start-Sleep -s 2
    };

Supporting Resources

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.