1

一直在写脚本:

foreach ($Username in (Import-Csv -Path "C:\Users\...\nope.csv")) {

    set-aduser $Username.Username -remove @{Proxyaddresses="smtp:$Username.Username@domain.com"}
        Write-Output "remove proxy"
    set-aduser $Username.Username -replace @{userPrincipalName="$Username.Username@domain.com"}
        Write-Output "replace principal"
    set-aduser $Username.Username -add @{Proxyaddresses="smtp:$Username.Username@domain.com"}
        Write-Output "add proxy"

}

代码运行但最终将这个垃圾 -> @{Username=###}.Username@domain.com 放在属性编辑器中。

任何帮助将不胜感激,现在正在尝试不同的方式,比如 8 小时。

4

1 回答 1

0

基本上,双引号会扩展对象$UserName,但不允许您引用对象的属性UserName。解决此问题的一种简单方法是使用Subexpression operator $( )

$object = [pscustomobject]@{
    Hello = 'World!'
}

$object.Hello      # => World!
"$object.Hello"    # => @{Hello=World!}.Hello
"$($object.Hello)" # => World!

另一方面,在这种情况下,一个更简单的解决方案是UserName在枚举集合时引用该属性:

foreach ($UserName in (Import-Csv -Path "C:\Users\...\nope.csv").UserName) {
    $upn = "$UserName@newDomain.com"
    Set-ADUser $UserName -Remove @{ ProxyAddresses = "smtp:$UserName@currentDomain.com" }
    Write-Output "Remove ProxyAddresses for $UserName"
    Set-ADUser $UserName -Replace @{ userPrincipalName = $upn }
    Write-Output "Replace UserPrincipalName for $UserName"
    Set-ADUser $UserName -Add @{ ProxyAddresses = "smtp:$upn" }
    Write-Output "Add ProxyAddresses for $UserName"
}
于 2022-01-27T22:26:56.613 回答