0

I'm trying to figure out how to retrieve an error from adding a already there computer in Active Directory. Here's the script that I'm using to add my machine in my domain.

Add-Computer -DomainName "myDomain" -OUPath "ou=Postes de travail,ou=Ordinateurs,ou=TRB,DC=,dc=,dc=,dc=" -credential (New-Object System.Management.Automation.PSCredential ("myUser", (ConvertTo-SecureString "myPassword" -AsPlainText -Force))) -PassThru -ErrorVariable $test -OutVariable $test1

In my Powershell ISE I see the error saying that my machine already exist but I'm trying to trap that so I can ask the user if he wants to remove it and then try to re-add the computer.

Thank you

jlliagre
  • 8,861
  • 18
  • 36

1 Answers1

2

Use it with the -ErrorAction parameter:

Add-Computer ... -ErrorAction SilentlyContinue -ErrorVariable computerError

The ErrorVariable is an array, so the resulting error will be stored in:

$computerError[0]

To use the same variable over and over again, use a + in front of the var name:

Add-Computer -ErrorVariable +manyErrors

And the last error will always be:

$manyErrors[$manyerrors.count - 1]
Mathias R. Jessen
  • 25,161
  • 4
  • 63
  • 95
  • Thank you it worked great. Now I get the complete error in my variable. How can I get the error number instead on the error phrase ? – ChangeMyNameForPA Jun 27 '13 at 14:23
  • If the exception has a native Win32 error code you should be able to access it at `$manyErrors[$manyerrors.count - 1].Exception.InnerException.NativeErrorCode` – Mathias R. Jessen Jun 27 '13 at 14:37
  • It doesn't have a native Win32 error but I managed to use .CategoryInfo.Category.value__ an it returns 7 so I guess I'm good. Unless you tell me otherwise. – ChangeMyNameForPA Jun 27 '13 at 15:02