PowerShell正则表达式DisplayName

时间:2016-11-15 11:27:21

标签: regex powershell

我需要让一群用户通过正则表达式查询,在其DisplayName的末尾查找“IM”或“(IM)”,然后将其删除。我当然会先出口备份。

我已经使用了.contains方法,但如果我使用它,任何Tim或Imogen都会对我有点生气。

$users = Get-DistributionGroupMember 'DGName' | ? { $_.RecipientType -eq 'UserMailbox' }
$mailboxes = $users | Get-Mailbox
$output = @()

$mailboxes | Select-Object Alias, DisplayName | Export-Csv D:\Scripts\PreDisplayNames.csv -NoTypeInformation

foreach ($mb in $mailboxes){
    if ($mb.DisplayName.EndsWith(" (IM)")){
        $newString = $mb.DisplayName.TrimEnd(" (IM)")
        $newStringTD = $mb.DisplayName.TrimEnd(" (IM)") + " (TD)"
        $resultstring =  "Setting DisplayName to $newString"
        $mb | Set-Mailbox -DisplayName $newString -WhatIf

    }
    elseif($mb.DisplayName.EndsWith(" IM")){
        $newString = $mb.DisplayName.TrimEnd(" IM")
        $newStringTD = $mb.DisplayName.TrimEnd(" (IM)") + " (TD)"
        $resultstring = "Setting DisplayName to $newString"
        $mb | Set-Mailbox -DisplayName $newString -WhatIf
    }
    else{
        $newString = 'DNIncorrect'
        $resultstring = 'Incorrect DisplayName'
    }
    $props = [ordered]@{
            'DisplayName' = $mb.DisplayName
            'NewDisplayName' = $newString
            'NewDisplayName TD' = $newStringTD
            }
    $object = New-Object -TypeName PSObject -Property $props
    $output += $object
}

$output | Export-Csv "D:\scripts\DisplayNames.csv" -NoTypeInformation

2 个答案:

答案 0 :(得分:0)

这里不需要正则表达式,只需使用-like来过滤收集邮箱时的对象

$mailboxes = $users | Get-Mailbox | Where-object {($_.DisplayName -like "*IM") -or ($_.DisplayName -like "*(IM)")}

答案 1 :(得分:0)

如果您仍然需要正则表达式,我通常使用以下内容为特定单词生成正则表达式。它可能适合你的情况。

$Eliminate = @("bak", "error", "research","Retry")
[regex]$eliminate_regex = '(?i)(' + (($Eliminate | foreach { [regex]::escape($_) }) -join "|") + ')'