简体   繁体   中英

Test if computer object exists in Active Directory in PowerShell

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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM