Checking if Distribution Group Exists in Powershell

12,447

Solution 1

You can use SilentlyContinue erroraction so that no exception/error shows:

$done = $false
while(-not $done)
{
   $newGroupName = Read-Host "Enter group name"
   $existingGroup = Get-DistributionGroup -Id $newGroupName -ErrorAction 'SilentlyContinue'

   if(-not $existingGroup)
   {
      # create distribution group here
      $done = $true
   }
   else
   {
      Write-Host "Group already exists"
   }
}

Solution 2

This should do the trick:

((Get-DistributionGroup $NewGroupName -ErrorAction 'SilentlyContinue').IsValid) -eq $true
Share:
12,447
Admin
Author by

Admin

Updated on June 18, 2022

Comments

  • Admin
    Admin almost 2 years

    I am writing a script to quickly create a new distribution group and populate it with a CSV. I am having trouble testing to see if the group name already exists.

    If I do a get-distributiongroup -id $NewGroupName and it does not exist I get an exception, which is what I expect to happen. If the group does exist then it lists the group, which is also what I expect. However, I can not find a good way to test if the group exists before I try to create it. I have tried using a try/catch, and also doing this:

    Get-DistributionGroup -id $NewGroupName -ErrorAction "Stop" 
    

    which makes the try/catch work better (as I understand non-terminating errors).

    Basically, I need to have the user enter a new group name to check if it is viable. If so, then the group gets created, if not it should prompt the user to enter another name.