【发布时间】:2020-03-31 08:09:43
【问题描述】:
我尝试更新 AD 用户帐户的 ProxyAddresses 属性。我已经阅读了许多关于此的主题并应用了一种建议的方法 (this one),但它对我不起作用。为什么? 我使用了以下代码(它是更新更多用户数据的脚本的一部分):
$ADUser = SearchADUser -Kogo "sAMAccountName -eq '$($WzorUser.sAMAccountName)'"
...
1.$ProxyOK = $false
2.$Proxies = $ADUser.ProxyAddresses
3.$Proxies | ForEach-Object {
4. $_ = $_ -replace 'SMTP', 'smtp'
5. if ($_ -match $NoweMail) {
6. $_ = $_ -replace 'smtp', 'SMTP'
7. $ProxyOK = $true
8. }
9.}
10.if (!($ProxyOK)) { $Proxies += ("SMTP:$($NoweMail)") }
...
if (!([string]::IsNullOrEmpty($Proxies))) {
$AttrToReplace.Add("ProxyAddresses", $Proxies)
Set-ADUser -Identity $ADUser.sAMAccountName -Server $ADDC @Attr #-PassThru -WhatIf
在 Proxies 上循环时,它的元素会被正确处理:所有字母都小写,如果新邮件已经存在,则字母大写。 但是代理没有改变。每个元素是否需要以某种方式保存或替换到对象中?
2020-04-02 更新
由于支持者的努力(@Theo 再次感谢您的协助)专注于替换方法,我尝试更详细地解释我的问题。
目标用户 proxyAddresses 值(女性回到 AD 中已记录的娘家姓的情况很少见):
SMTP:anna.nowak22@lp.pl
smtp:a.b@moc.com
初始值(第 2 行):
[DBG]: PS X:\>> $Proxies
smtp:anna.nowak22@lp.pl
SMTP:a.b@moc.com
在每个代理元素上循环时(第 9 行):
[DBG]: PS X:\>> $_
SMTP:anna.nowak22@lp.pl
[DBG]: PS X:\>> $Proxies
smtp:anna.nowak22@lp.pl
SMTP:a.b@moc.com
[DBG]: PS X:\>> $_
smtp:a.b@moc.com
[DBG]: PS X:\>> $Proxies
smtp:anna.nowak22@lp.pl
SMTP:a.b@moc.com
可以看出,$Proxies 没有反映变化。
如果只有一个 ProxyAddresses 值不等于新邮件,则将新邮件作为 SMTP 添加到现有邮件中,该邮件也保留为 SMTP(两个主要 ProxyAddresses)。
我尝试创建一个新变量并分别为其分配每个值,但我不知道如何处理它。
$newProxies = $null
$Proxies | ForEach-Object {
$_ = $_ -creplace 'SMTP', 'smtp'
if ($_ -match $NoweMail) {
$_ = $_ -creplace 'smtp', 'SMTP'
$ProxyOK = $true
}
$newProxies.add($_)
}
上面会产生错误
您不能在空值表达式上调用方法
$newProxies += $_ 创建一个字符串 SMTP:anna.nowak22@lp.pl
smtp:a.b@moc.com 作为单个 ProxyAddress 添加。
正如我所指出的,$Proxies 是一个特殊的 AD 对象,我不知道如何创建这种类型的对象以及如何向其中添加新元素。
【问题讨论】:
-
我通常为用户清除现有的 ProxyAddresses,然后添加新的代理数组:
Set-ADUser -Identity $ADUser.sAMAccountName -Clear ProxyAddresses后跟Set-ADUser -Identity $ADUser.sAMAccountName -Add @{proxyAddresses = $Proxies}。附言-replace不区分大小写。在这种情况下,我更喜欢使用-creplace。空 $Proxies 数组的测试也是多余的。如果必须,请使用if ($Proxies)或if ($Proxies.Count) -
@Theo。替换工作正常。代理的每个元素都处理得很好。如果匹配模式,拳头小写然后大写。替换后变量 $_ 大小写正确。但它不会更新代理。
-
这就是为什么我向你展示了我是如何做到的。在您的代码中,您将 $Proxies 添加到名为
$AttrToReplace的 Hashtable (?) 中,但在 Set-ADUser cmdlet 中,您使用另一个变量Attr。我要说明的一点是,您将 ProxyAddresses 数组与您要为用户设置的所有其他属性(如果有的话)分开。执行$ADUser | Set-ADUser -Clear ProxyAddresses后跟$ADUser | Set-ADUser -Add @{proxyAddresses = $Proxies}您可以在一个命令中执行:$ADUser | Set-ADUser -Replace @{proxyAddresses = $Proxies},但我总是喜欢先清除它。 -
你看到我的更新了吗?它处理根据需要重新创建
$Proxies。最后,要添加的集合必须是 强类型 字符串集合。为此,请使用[string[]]$Proxies转换数组,因为您已经测试过了。您的最新代码将不起作用,因为在您尝试对其使用.add方法时,变量$newProxies什么都没有。 -
强类型意味着集合只能包含指定类型的元素,在本例中为
string。一个普通的数组可以包含多种类型。
标签: powershell