Handling Domain Join Errors
<p>I have created a basic script to add a PC to the domain.  Although this works there is room for error, and I want to put in some error handling. </p>

<pre><code>do {
  Add-Computer -DomainName $Domain -Credential(get-credential)
} while (!$?)
</code></pre>

<p>Using !$? runs the while loop while the last command is not successful. </p>

<p>However, there are various errors that return. Whether the PC is off the network, incorrect user ID or password, or domain specification, I want to be able to handle those errors and display something meaningful. </p>

<p>One of the errors returned </p>

<pre>Add-Computer : This command cannot be executed on target computer('PCName') due to
following error: Logon failure: unknown user name or bad password.
At line:1 char:13
+ Add-Computer &lt;&lt;&lt;&lt;  -DomainName $Domain -Credential(get-credential); 
    + CategoryInfo          : InvalidOperation: (PCNAME:String) [Add-Computer], InvalidOperationException
    + FullyQualifiedErrorId : InvalidOperationException,Microsoft.PowerShell.Commands.AddComputerCommand</pre>

<p>Working with error handlers in lets say VBA, an error ID is given, and using if statements you can do something with it. </p>

<p>The FullyQualifiedErrorID in the error above is the same across all errors received for different reasons, so I do not believe I can use that. </p>

<p>How can I capture the specific error "Logon failure: unknown user name or bad password." or other errors and display a meaningful message so the admin can take appropriate action?</p>