Home > OS >  Test if computer object exists in Active Directory in PowerShell
Test if computer object exists in Active Directory in PowerShell

Time:12-08

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.

CodePudding user response:

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"
}

CodePudding user response:

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

  • Related