'Powershell script for catching exception for adding group members to local group
I want to add members in Remote Desktop Users group and if i find "The specified account name is already a member of the group" exception then skip and move to other member to add.
I have tried below but it didnt catch the exception and keep giving me same error.. Please advice.
$LocalGroup = [ADSI]"WinNT://$env:computername/Remote Desktop Users,group"
$DomainGroup = [ADSI]"WinNT://Domain/Test Success Team"
$LocalGroup.Add($DomainGroup.path)
Try {
$LocalGroup.Add($DomainGroup.path)
} Catch [Microsoft.ActiveDirectory.Management.ADException] {
if ($_ -like "The specified account name is already a member of the group.")
{
Write-Host “!!! LOCAL GROUP ALREADY EXISTS !!!”
}
elseif ($_ -eq $null)
{
Write-Host " lOCAL GROUP CREATED SUCCESSFULLY "
}
I am getting below error...
Exception calling "add" with "1" argument(s): "The specified account name is already a
member of the group.
"
At line:4 char:1
+ $LocalGroup.Add($DomainGroup.path)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : CatchFromBaseAdapterMethodInvokeTI
Unable to find type [Microsoft.ActiveDirectory.Management.ADException].
At line:11 char:9
+ } Catch [Microsoft.ActiveDirectory.Management.ADException] {
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (Microsoft.Activ...ent.ADException:TypeN
ame) [], RuntimeException
+ FullyQualifiedErrorId : TypeNotFound
Solution 1:[1]
I woulduse $($Error[0].Exception.InnerException.Message) insted $_
if($($Error[0].Exception.InnerException.Message).Contains("The specified account name is already a member of the group."))
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | mexicali82 |