PowerShell 中的空格和$null变量处理?



我正在尝试创建一个脚本,该脚本将抓取OU中的所有用户,并将当前主别名更改为辅助别名,同时添加新的主smtp地址并保留任何其他辅助别名。我们的用户有0个别名,有些有1个,有些有2个,还有一些有3个。当$sp1、$sp2、$sp3、$sp4、$sp5中的任何一个为空白或为null时,我遇到了一个问题。我还在学习powershell,所以我不知道如何处理它而不会有很多痛苦哈哈。

$Users = Get-AdUser -Filter * -SearchBase "OU=TestScriptedSMTPAddrChange,OU=***,DC=***,DC=com" -Properties proxyAddresses | Select-Object SamAccountName, proxyAddresses #Change first OU= to the OU you want to change

Foreach ($SAN in $Users){
$SecondaryProxyRaw = $SAN.proxyAddresses #grab proxyAddresses and dump them
$SecondaryProxyRed = $SecondaryProxyRaw.replace('SMTP','smtp') #change primary SMTP addr to secondary smtp addr
$sp1,$sp2,$sp3,$sp4,$sp5 = $SecondaryProxyRed.split(" ",1) #split the proxyAddresses array into variables
$NewPrimaryProxy = "SMTP:$($SAN.SamAccountName)@newdomain.com"} #assign new primary SMTP address
Set-ADUser -Identity $SAN.SamAccountName -replace @{proxyAddresses = "$NewPrimaryProxy","$sp1","$sp2","$sp3","$sp4","$sp5"}
}
Get-AdUser -Filter * -SearchBase "OU=TestScriptedSMTPAddrChange,OU=***,DC=***,DC=com" -Properties proxyAddresses | Select-Object SamAccountName, UserPrincipalName, @{Name="Proxyaddresses";Expression={$_.proxyAddresses -join "*"}}

您不应该依赖于用户在其proxyAddresses属性中有1、3或77个地址,试图将这些地址拆分为固定数量的变量。

只需获取所有地址,将大写的SMTP:替换为小写的"smtp:",筛选出可能等于新代理地址的地址,并将新的主地址添加到数组中
然后,用强类型(即强制转换为string[]](新数组替换整个proxyAddresses数组。

$Users = Get-AdUser -Filter * -SearchBase "OU=TestScriptedSMTPAddrChange,OU=***,DC=***,DC=com" -Properties proxyAddresses
foreach ($SAN in $Users) {
$NewPrimaryProxy = 'SMTP:{0}@newdomain.com' -f $SAN.SamAccountName
# if you like you can sort the proxies but for the system this will have no effect
$proxies = @($SAN.ProxyAddresses -replace '^SMTP:', 'smtp:' | Where-Object { $_ -ne $NewPrimaryProxy }) + $NewPrimaryProxy
# Note: proxyAddresses needs a Strongly typed string array, that is why we cast $proxies array with [string[]]
$SAN | Set-ADUser -Replace @{proxyAddresses = [string[]]$proxies}
}

.split(" ",1)

根本不拆分-根据定义,它按原样返回输入字符串,因为您只要求1令牌-请参阅.NET[string]类型的.Split()方法的文档。

要通过运行空格进行拆分,可以使用PowerShell的-split运算符的一元形式:

# Split by whitespace and collect tokens in an array.
# -ne '' filters out empty elements, so that if 
# $SecondaryProxyRed is effectively empty, $sps becomes an empty array.
$sps = -split $SecondaryProxyRed -ne ''

然后,您可以创建一个数组,将$NewPrimaryProxy作为第一个元素,然后是$sps的元素(如果有的话(:

Set-ADUser -Identity $SAN.SamAccountName -replace @{
proxyAddresses = @($NewPrimaryProxy) + $sps
}

最新更新