向用户添加多个代理地址

时间:2018-08-17 01:07:37

标签: powershell active-directory

我有几个需要数百个代理地址的用户。我正在使用以下内容,但仅插入“ smtp:';

$proxyaddress 
='admin@test.edu.au','admin@test.com.au','ctiadmin@test.edu.au',
'fax@test.edu.au','info@test.edu.au'.....
Set-ADUser -Identity hello@test.edu.au -Add @{'proxyAddresses' = 
$proxyAddresses | % { "smtp:$_" }}

我将不胜感激

1 个答案:

答案 0 :(得分:0)

您的代码中的错误是您将一个名为$proxyaddress的数组实例化,但是稍后使用$proxyAddresses

无论如何,我建议不要简单地添加一堆可能已经在用户proxyAddresses列表中的地址。

尝试

function Add-UserEmailAliases {
    [CmdletBinding(DefaultParameterSetName = 'ById')]
    param(
        [Parameter(ValueFromPipeline = $true, Mandatory = $true, ParameterSetName='ById', Position = 0)]
        [string]$Identity,             # distinguishedName, objectGUID or sAMAccountName

        [Parameter(Mandatory = $true, ParameterSetName='ByUPN', Position = 0)]
        [string]$UserPrincipalName,    # UPN

        [Parameter(Mandatory = $true, ParameterSetName='ByEmail', Position = 0)]
        [string]$EmailAddress,         # emailadress

        [Parameter(Mandatory = $true, Position = 1)]
        [string[]]$AliasesToAdd
    )

    # add the 'smtp:' prefix to each address; if already present, remove first
    $newProxies = @($AliasesToAdd | ForEach-Object { "smpt:{0}" -f ($_ -replace '^smpt:', '') })

    # get the user object
    switch ($PsCmdlet.ParameterSetName) {
        'ByUPN'    { $user = Get-ADUser -Filter "UserPrincipalName -eq '$UserPrincipalName'" -Properties ProxyAddresses ; break }
        'ByEmail'  { $user = Get-ADUser -Filter "EmailAddress -eq '$EmailAddress'" -Properties ProxyAddresses ; break }
        default    { $user = Get-ADUser -Identity $Identity -Properties ProxyAddresses }
    } 

    # store the primary email address
    $primaryAddress = $user.ProxyAddresses | Where-Object { $_ -cmatch '^SMTP:.*' }
    # read all other existing addresses
    $otherAddresses = @($user.ProxyAddresses | Where-Object { $_ -cnotmatch '^SMTP:.*' })
    # combine with the addresses to add and remove any duplicates
    $otherAddresses = ($otherAddresses + $newProxies) | Sort-Object -Unique

    # merge the existing and added addresses with the primary email address
    $newProxies = @($primaryAddress) + $otherAddresses

    # finally replace the users addresses. I like:
    $user | Set-ADUser -Clear ProxyAddresses
    $user | Set-ADUser -Add @{'proxyAddresses'=$newProxies }

    # but you could also do
    #$user | Set-ADUser -Replace @{'proxyAddresses' = $newProxies}
}

像这样使用它:

$proxyaddresses = @('admin@test.edu.au','admin@test.com.au','ctiadmin@test.edu.au',
                    'fax@test.edu.au','info@test.edu.au')

Add-UserEmailAliases -UserPrincipalName "hello@test.edu.au" -AliasesToAdd $proxyaddresses