检查Powershell中是否存在通讯组

use*_*385 2 powershell exchange-server

我正在编写一个脚本来快速创建一个新的通讯组并用CSV填充它.我无法测试以查看组名是否已存在.

如果我做了get-distributiongroup -id $NewGroupName它并且它不存在我得到一个异常,这是我期望发生的.如果该组确实存在,那么它会列出该组,这也是我所期望的.但是,在尝试创建组之前,我找不到测试组是否存在的好方法.我尝试过使用try/catch,并且还这样做:

Get-DistributionGroup -id $NewGroupName -ErrorAction "Stop" 
Run Code Online (Sandbox Code Playgroud)

这使得try/catch更好地工作(因为我理解非终止错误).

基本上,我需要让用户输入一个新的组名来检查它是否可行.如果是,则创建组,否则应提示用户输入其他名称.

lat*_*kin 7

您可以使用SilentlyContinue错误,以便没有异常/错误显示:

$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"
   }
}
Run Code Online (Sandbox Code Playgroud)