I have a simple script to display the members of a Local Group on a server, and I’m having problems trying to add some Error Checking to it. I want to display a message and end the script if the specified group doesn’t exist.
$Server = "xx.x.xxx.xx"
$Group = "fred"
$g = [ADSI]("WinNT://$server/$group,group")
Running the above results in this error -
format-default : The following exception occurred while retrieving member "PSComputerName": "The group name could not b
e found.
"
+ CategoryInfo : NotSpecified: (:) [format-default], ExtendedTypeSystemException
+ FullyQualifiedErrorId : CatchFromBaseGetMember,Microsoft.PowerShell.Commands.FormatDefaultCommand
If I could capture this text from the message, that would be great - "The group name could not be found.” But at this point just identify there is an error would be good.
The –ErrorAction parameter doesn’t work on this $g = [ADSI]("WinNT://$server/$group,group") Statement.
I’ve tried looking at the $Error[0].Exception.Message but can’t seem to get what I need. I’ve tried using Try/Catch as follow to at least detect an error, but with no luck, as it doesn't seem to Catch the error -
try
{
$g = [ADSI]("WinNT://$server/$group,group")
}
catch
{
Write-Warning "Group not found"
}
Any thoughts?
Thanks