I'm working on a PowerShell script to change a local account name. Of course, the first step is to check that the account exists:
$user=[ADSI]"WinNT://$server/$oldName,user"
If the account exists, then no problem. But if it doesn't, then I get this error:
format-default : The following exception occurred while retrieving member >"distinguishedName": "The user name could not be found." + CategoryInfo : NotSpecified: (:) [format-default], ExtendedTypeSystemException + FullyQualifiedErrorId : CatchFromBaseGetMember,Microsoft.PowerShell.Commands.FormatDefaultCommand
I can't figure out how to look for that error, report something like "$oldName not found" and continue on. From what I can tell, it isn't being thrown into an error variable, so I can't search for a "user name could not be found" string. Try-Catch-Finally seems to ignore the error.
I admit I'm weak on error-handling. It seems there's countless ways for something to fail, and my users always find new ones when using my scripts.
It seems like the command is actually throwing a terminating error. From about_preference_variables
"Neither $ErrorActionPreference nor the ErrorAction common parameter affect how Windows PowerShell responds to terminating errors (those that stop cmdlet processing)."
So when the command runs it is terminating the script even before it can move on to try and process a catch block.
Interestingly if you put it into a variable this behavior stops happening. I'd be curious to see if anyone has a better answer, but it looks like the solution from what I can see, would be an if statement based on the results of the variable.
$User = [ADSI]"WinNT://badserver/Name,user"
If (! $User.Name)
{
Throw "Issue retrieving user"
}
#Rest of script can continue here