用于交换 Proxyaddresses 和 PrincipalName 的 Powershell 脚本

Powershell Script to swap Proxyaddresses and PrincipalName

正在编写脚本:

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 小时的不同方法。

基本上 double-quotes 正在扩展对象 $UserName 但是不允许您 reference 属性 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"
}