Last week there was a question in the Technet forums by an admin who was writing a script to enable new or disabled users for Lync and the admin was trying to figure out how to handle the error that is returned when a Lync user doesn’t exist or is disabled (thread is here). While there are probably a number of ways to do this I was intrigued by how one might find specific errors and act upon them.
As you can see in the Technet thread I gave a quick workaround by suggesting the use of -errorvariable to write the error output into a variable. You can then check the variable to see if it’s null or not.
$CSUser= Get-CsUser –Identity $username -DomainController $targetdc -errorvariable +err
if ($err -eq "$null")…
Pretty handy but sometimes we want to look for specific errors and act upon them. You can use Select-String to look for a particular pattern:
if ($err | select-string -simplematch -pattern "Management object not found for identity")
Select-String is also handy because you can look for multiple patterns in the string:
if ($err | select-string -simplematch -pattern "Management object not", "found for identity")
So if there were some specific errors I wanted to handle I could do so, anything outside of that could simply trigger a log entry or alert. You can also get more detailed information on the error (or a better logfile format) with $err[0] |fl * -Force, which gives output that looks like this:
PSMessageDetails :
Exception : Microsoft.Rtc.Management.AD.ManagementException: Management object not found for identity “domain\user".
TargetObject : domain\user
CategoryInfo : InvalidData: (domain\user:UserIdParameter) [Get-CsUser], ManagementException
FullyQualifiedErrorId : Identity,Microsoft.Rtc.Management.AD.Cmdlets.GetOcsUserCmdlet
ErrorDetails :
InvocationInfo : System.Management.Automation.InvocationInfo
PipelineIterationInfo : {0, 1, 0}
Here’s a final script that shows this in use:
get-csuser domain\user -errorvariable +err | out-null
if ($err | select-string -simplematch -pattern "Management object not found for identity")
{
# Replace the echo with stuff to do to the disabled user
echo "There was an error in processing"
}
else
{
# Replace the echo with stuff to do to the enabled user
echo "There was no error"
}
Powershell has a lot of options for catching and handling errors. This is a very basic way for folks who have basic error handling needs. For more complex requirements take a look at the various other methods and articles (such as Try…Catch) which are out there.