Recently I created a PowerShell script that should delete a group that has a specific name. If the script runs the second time, it throws an exception since the group is already deleted.
If you want to get/delete/add a group from/to a SPGroupCollection (like SiteGroups or Groups of an SPWeb) the methods throw typically exceptions of different kinds if the group does not exist (or already does exist in case of addition):
$web.SiteGroups.Remove(12345) throws
Specified argument was out of the range of valid values.
$web.SiteGroups.Remove("YourGroupName") throws
Group cannot be found.
$web.SiteGroups.GetByID(12345) and
$web.SiteGroups.GetByName("YourGroupName") throw
Group cannot be found.
$web.SiteGroups.Add("YourGroupName", $usr, $null, "Group description") throws
The specified name is already in use.
I wanted to eliminate the error messages. If these commands were PowerShell Cmdlets, we could use the common ErrorAction parameter with the value SilentlyContinue (see more here), however with standard .NET object calls only the Try/Catch block would be available.
Throwing and handling exceptions has always a performance penalty. How could we check if the group exists before trying to get/delete/add it from/to the collection?
After a short search on the .NET based samples I found:
- A generic- and lambda expression-based solution, that is nice, but not easy to transfer to PowerShell.
- An interesting solution, that uses the Xml property of the SPGroupCollection object .
- A solution that is based on the GetCollection method of the SPGroupCollection object.
I chose the third sample to transfer to PowerShell. The equivalent PowerShell condition to check the group by ID:
@($web.SiteGroups.GetCollection(@(12345))).Count -eq 1
To check the group by name, we can use:
@($web.SiteGroups.GetCollection(@("YourGroupName"))).Count -eq 1
The parameter of the GetCollection method is an array, so we can use the same method to check if all or any of multiple groups exists.
For example, to check by ID if both of the groups we need exist:
@($web.SiteGroups.GetCollection(@(12345, 54321))).Count -eq 2
To check by name if any of the groups we need exists:
@($web.SiteGroups.GetCollection(@("YourGroupName1", "YourGroupName2"))).Count –gt 0
