1

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.

user01230
  • 563
  • 1
  • 6
  • 16

2 Answers2

1

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}
}
RM1358
  • 308
  • 1
  • 2
  • 9
0

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
        }
    }
TheMadTechnician
  • 34,906
  • 3
  • 42
  • 56
  • I think you need to add `-ErrorAction Stop` for the try catch. I don't think its a terminating error. – Matt Feb 23 '15 at 21:04
  • Thank you very much! I knew there was a way to use the try-catch method! – user01230 Feb 23 '15 at 21:50
  • 1st example: add parameters: Add-ComputerToAD -Domain $Domain 2nd, use do/while. because while() will never invoke Add-Computer – papo Aug 05 '17 at 19:51