添加检查 ExternalEmailAddress 是否已存在于 CSV 中,以及它是否不执行任何操作

Add a Check if ExternalEmailAddress already exists in the CSV and if it does do nothing

我该怎么做?有任何想法吗?如果 ExternalEmailAddress 已经存在,我只是想确保我的脚本不会尝试创建新的 mailContact。

If (Test-Path $CSVFileName) {

    #Import the CSV file
    $csvfile = Import-CSV $CSVFileName
        
    #Loop through CSV file
    foreach ($line in $csvfile) {

        try {
            #Create the mail contact    
            New-MailContact -domaincontroller $dc -Name $line.Name -ExternalEmailAddress $line.ExternalEmailAddress  -OrganizationalUnit $OU -ErrorAction STOP
            Set-Contact -domaincontroller $dc -Identity $line.Name -Department $line.Department -Title "Sales Team" -StreetAddress $line.StreetAddress -City $line.City -StateOrProvince $line.StateOrProvince -PostalCode $line.PostalCode -Office $line.Office -CountryOrRegion $line.CountryOrRegion
            "$($line.Name) was created successfully." | Out-File $logfile -Append
        }
        catch {
            
            $message = "A problem occured trying to create the $($line.Name) contact"
            $message | Out-File $logfile -Append
            Write-Warning $message
            Write-Warning $_.Exception.Message
            $_.Exception.Message | Out-File $logfile -Append
        }

    }
}

我没有发现您的方法有任何根本问题。如果您担心测试它,请创建一个 t运行cated 版本的 CSV 文件,以查看脚本如何与某些测试帐户或诸如此类的东西反应。您还可以在 NewSet 命令上使用 -WhatIf 参数来检查哪些对象将受到影响,但不进行更改。

我必须假定 $OU 变量是在别处定义的。我唯一建议的另一件事是使用 splatting 使其更具可读性。这可能看起来像这样:

$NewParams = @{
   DomainController     = $dc
   OrganizationalUnit   = $OU
   ErrorAction          = 'Stop'
}

$SetParams = @{
   DomainController = $dc      
   Title            = 'Sales Team'      
}

If (Test-Path $CSVFileName) {

   #Import the CSV file
   $csvfile = Import-CSV $CSVFileName
   
   # Adjust splatting hash tables per incoming line:
   $NewParams['Name']                 = $line.Name
   $NewParams['ExternalEmailAddress'] = $line.ExternalEmailAddress

   # Adjust splatting hash for the set command:
   $SetParams['Identity']             = $line.Name
   $SetParams['Department']           = $line.Department
   $SetParams['StreetAddress']        = $line.StreetAddress
   $SetParams['City']                 = $line.City
   $SetParams['StateOrProvince']      = $line.StateOrProvince
   $SetParams['PostalCode']           = $line.PostalCode
   $SetParams['Office']               = $line.Office
   $SetParams['CountryOrRegion']      = $line.CountryOrRegion

   #Loop through CSV file
   foreach ($line in $csvfile) {

       try {
           #Create the mail contact    
           New-MailContact @NewParams
           Set-Contact @SetParams
           "$($line.Name) was created successfully." | Out-File $logfile -Append
       }
       catch {
           
           $message = "A problem occured trying to create the $($line.Name) contact"
           $message | Out-File $logfile -Append
           Write-Warning $message
           Write-Warning $_.Exception.Message
           $_.Exception.Message | Out-File $logfile -Append
       }

   }
}

此示例设置了 2 个具有常量值的哈希表。然后在循环内,它会添加 and/or 更改散列中的变量参数,每行输入。他们只是将这些哈希值引用为 New-MailContact & Set-Contact 命令的参数。

Exchange 管理 Shell 不允许您复制 SMTP 地址。如果您尝试这样做,将 return 出现如下错误:

The proxy address "SMTP:Example@Example.com" is already being used by the proxy addresses or LegacyExchangeDN of "local.domian/Users/OtheMailEnabledObject". Please choose another proxy address.

但是,如果您想完全避免错误and/or防止将这些特定类型的错误写入日志,您可以做一些事情。

从代码的角度来看,最简单的做法是使用 Get-Recipient 命令简单地添加一个 If 块。

#...
    #Loop through CSV file
    foreach ($line in $csvfile) {
        If( !(Get-Recipient $line.ExternalEmailAddress) ) {
            try {
                #Create the mail contact    
                New-MailContact @NewParams
                Set-Contact @SetParams
                "$($line.Name) was created successfully." | Out-File $logfile -Append
            }
            catch {            
                $message = "A problem occured trying to create the $($line.Name) contact"
                $message | Out-File $logfile -Append
                Write-Warning $message
                Write-Warning $_.Exception.Message
                $_.Exception.Message | Out-File $logfile -Append
            }
        }
    }

注意:Get-RecipientGet-MailContact更彻底。

另一种方法可能是简单地以不同方式处理这些特定错误。

#...
    #Loop through CSV file
    foreach ($line in $csvfile) {
        try {
            #Create the mail contact    
            New-MailContact @NewParams
            Set-Contact @SetParams
            "$($line.Name) was created successfully." | Out-File $logfile -Append
        }
        catch {
            If( $Error[0].CategoryInfo.Reason -ne 'ProxyAddressExistsException' ){
                $message = "A problem occured trying to create the $($line.Name) contact"
                $message | Out-File $logfile -Append
                Write-Warning $message
                Write-Warning $_.Exception.Message
                $_.Exception.Message | Out-File $logfile -Append
            }
        }
    }

所以在这种情况下,您仅在错误 不是 重复代理地址时才记录。您当然可以根据需要创建其他逻辑。

如果您有大量联系人,创建这两种方法可能会很慢。这是因为他们会执行很多他们不需要的命令。对于后一种方法,性能损失与实际发生的重复错误数有关。对于前者,您会在每次循环迭代中受到影响,因为无论 New-MailContact 命令是否成功,您总是在检查。

因此,最后一种方法是创建一个现有代理地址列表,您可以在尝试创建新联系人之前对其进行检查。

要编译所有 SMTP 代理地址的列表:

$ExistingAddresses = 
Get-Recipient ResultSize Unlimited | 
Select-Object -ExpandProperty EmailAddresses | 
Where-Object{$_.PrefixString -eq 'SMTP'} |
Select-Object -ExpandProperty SmtpAddress

但是,Get-Recipient 可能在通过大型查询 return 编辑的大型集合进行分页时遇到问题。取决于您的环境。如果确实有问题,您可以使用 AD cmdlet 的替代方法,在任何情况下都会快得多。

$ExistingAddresses =
Get-ADObject -Filter "mailnickname -like '*'" -Properties 'ProxyAddresses' |
 ForEach-Object{ 
    ForEach($ProxyAddress in $_.ProxyAddresses)
    {
        If( $ProxyAddress -match "^smtp" ) {
            $ProxyAddress.Split(':')[1]
        }
    }
}

填充 $ExistingAddresses 后,您可以更改循环以首先检查列表:

foreach ($line in $csvfile) {
    If( $line.ExternalEmailAddress -notin $ExistingAddresses ) {
        try {
            #Create the mail contact    
            New-MailContact @NewParams
            Set-Contact @SetParams
            "$($line.Name) was created successfully." | Out-File $logfile -Append
        }
        catch {
            $message = "A problem occured trying to create the $($line.Name) contact"
            $message | Out-File $logfile -Append
            Write-Warning $message
            Write-Warning $_.Exception.Message
            $_.Exception.Message | Out-File $logfile -Append
        }
    }
}

同样,如果需要,您可以构建额外的逻辑。例如,Else{...} 如果您想报告发现重复等...

基于其他评论。如果你想 运行 对那些已经存在的联系人设置命令。这是 1 个示例:

#Loop through CSV file
foreach ($line in $csvfile) {
    If( !(Get-Recipient $line.ExternalEmailAddress) ) {
        try {
            #Create the mail contact    
            New-MailContact @NewParams
            "$($line.Name) was created successfully." | Out-File $logfile -Append
        }
        catch {            
            $message = "A problem occured trying to create the $($line.Name) contact"
            $message | Out-File $logfile -Append
            Write-Warning $message
            Write-Warning $_.Exception.Message
            $_.Exception.Message | Out-File $logfile -Append
        }
    }
    # The contact either already exists or was just created, so long as you
    # Use the same domain controller go ahead and perform the Set...
    Set-Contact @SetParams
}

同样,有一千种方法可以安排这样的事情。并且,所有上述方法都可以修改以满足新要求。但是,这不会告诉您更新了哪些属性。如果您想要那种 属性 级别比较,我们将不得不编写更多代码。