user01230
user01230

Reputation: 623

Catch error and restart the if statement

I have a powershell script that adds a computer to a domain. Sometimes, when I run the script I get the following error and when I run it for the second time it works. How can I make the script to check if I get this error, and if so then to retry adding it to the domain? I have read that it is hard to try and catch errors like that. Is that correct? Is there a better/different way to catch the error?

Thank you!


Code:

if ($localIpAddress -eq $newIP)
        { # Add the computer to the domain
          write-host "Adding computer to my-domain.local.. "
          Add-Computer -DomainName my-domain.local | out-null
        } else {...}

Error:

This command cannot be executed on target computer('computer-name') due to following error: The specified domain either does not exist or could not be contacted.

Upvotes: 1

Views: 8851

Answers (2)

RM1358
RM1358

Reputation: 338

You can use the built in $Error variable. Clear it before executing code, then test if the count is gt 0 for post error code.

$Error.Clear()
Add-Computer -DomainName my-domain.local | out-null
if($Error.count -gt 0){
    Start-Sleep -seconds 5
    Add-Computer -DomainName my-domain.local | out-null}
}

Upvotes: 1

TheMadTechnician
TheMadTechnician

Reputation: 36277

You could setup a function to call itself on the Catch. Something like:

function Add-ComputerToAD{
Param([String]$Domain="my-domain.local")
    Try{
        Add-Computer -DomainName $Domain | out-null
    }
    Catch{
        Add-ComputerToAD
    }
}

if ($localIpAddress -eq $newIP)
        { # Add the computer to the domain
          write-host "Adding computer to my-domain.local.. "
          Add-ComputerToAD
        } else {...}

I haven't tried it to be honest, but I don't see why it wouldn't work. It is not specific to that error, so it'll infinitely loop on repeating errors (i.e. another computer with the same name exists in AD already, or you specify an invalid domain name).

Otherwise you could use a While loop. Something like

if ($localIpAddress -eq $newIP)
    { # Add the computer to the domain
        write-host "Adding computer to my-domain.local.. "
        While($Error[0].Exception -match "The specified domain either does not exist or could not be contacted"){
            Add-Computer -DomainName my-domain.local | out-null
        }
    }

Upvotes: 0

Related Questions