繁体   English   中英

使用 PowerShell 添加特定格式的 proxyAddresses 属性?

[英]Using PowerShell to add the proxyAddresses attribute with specific format?

我需要为特定 OU 中的用户添加新的 email 别名,具体格式如下:

user Alias / sAMAccountName = First Lastname
newAlias = FLastname@NewBrandX.com

User with Apostrophe
user Alias / sAMAccountName = John O'Dea
newAlias = JOdea@NewBrandX.com

User with either First or Lastname with spaces
user Alias / sAMAccountName = Peter Van Denberg
newAlias = PVanDenberg@NewBrandX.com

不过我的脚本功底很有限,不知道有没有人可以帮忙修改下面的脚本:

$newproxy = "@NewBrandX.com"
$userou = 'OU=Users,OU=Seattle,DC=usa,DC=contoso,DC=com'
$paramGetADUser = @{
   Filter      = 'Enable -eq $true'
   SearchBase = $userou
   Properties = 'SamAccountName', 'ProxyAddresses', 'givenName', 'Surname'
}


$users = Get-ADUser @paramGetADUser


Foreach ($user in $users)
{
   $FirstName = $user.givenName.ToLower() -replace '\s', ''
   $LastName = $user.surname.ToLower() -replace '\s', '' -replace "'", ''
   Set-ADUser -Identity $user.samaccountname -Add @{ proxyAddresses = "smtp:" + $FirstName + $LastName + $newproxy }
}

在我看来,您想以格式创建一个新的代理地址

  • GivenName 的第一个字符
  • 没有撇号或空格的姓氏
  • 其次是"@NewBrandX.com"

但是,您的代码采用完整的 GivenName。

要添加到 ProxyAddresses 数组,您需要替换整个 [string[]] 数组

$newproxy = "@NewBrandX.com"
$userou   = 'OU=Users,OU=Seattle,DC=usa,DC=contoso,DC=com'
$paramGetADUser = @{
   Filter     = 'Enable -eq $true'
   SearchBase = $userou
   Properties = 'ProxyAddresses'  # SamAccountName, GivenName and Surname are returned by default
}


$users = Get-ADUser @paramGetADUser

foreach ($user in $users) {
    $newAddress = ("smtp:{0}{1}$newproxy" -f $user.GivenName.Trim()[0], ($user.Surname -replace "[\s']+").ToLower())
    $proxies    = @($user.ProxyAddresses)
    # test if this user already has this address in its ProxyAddresses attribute
    if ($proxies -contains $newAddress) {
        Write-Host "User $($user.Name) already has '$newAddress' as proxy address" 
    }
    else {
        Write-Host "Setting new proxy address '$newAddress' to user $($user.Name)" 
        $proxies += $newAddress
        # proxyAddresses needs a **strongly typed** string array, that is why we cast the $proxies array with [string[]]
        $user | Set-ADUser -Replace @{ proxyAddresses = [string[]]$proxies }
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM