PowerShell中的-split功能问题

yhived7q  于 2023-04-30  发布在  Shell
关注(0)|答案(1)|浏览(205)

你好,我在尝试循环导出csv表中的列时遇到了一些问题。

$userproxy = $null
    foreach($proxy in $foundUser.proxyAddresses) {
       
        if($proxy.substring(0,4) -like "smtp" -or $proxy.substring(0,4) -like "SMTP") {
            $userproxy += $proxy + "-" 
        }        
    }

这是用于导出用户proxyAddresses的代码,然后将其添加到表中。此表用于将用户从一个域迁移到另一个域,这是一个如何影响表的示例。

"Name","givenName","sn","sAMAccountName","mail","mailNickname","mS-DS-ConsistencyGuid","targetAddress","proxyAddresses"
"John Doe","John","Doe","B004796","jdoe@local.com","jdoe","7c8f6e36-7a21-254a-ae7b-85adb256a777","SMTP:jdoe@local.com","smtp:jdoe@local.grp-SMTP:jdoe@local.com-"

您的短信
然后在另一个DC上,在尝试使用csv文件中的数据时,我尝试在每个代理上循环

$proxyToAdd = $userInfo.proxyAddresses -split "-"
         foreach($proxy in $proxyToAdd){
            Write-Host $item
            Set-ADUser $foundUser.sAMAccountName -add @{proxyAddresses = $proxy}
         }

当启动时,它返回以下错误。

smtp:jdoe@local.grp
SMTP:jdoe@local.com

Set-ADUser : add
Au caractère D:\Scripts\Migration Eneria\Traitement_Migration.ps1:48 : 13
+             Set-ADUser $foundUser.sAMAccountName -add @{proxyAddresse ...
+             ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation : (proteauclementt:ADUser) [Set-ADUser], ADInvalidOperationException
    + FullyQualifiedErrorId : ActiveDirectoryServer:0,Microsoft.ActiveDirectory.Management.Commands.SetADUser

我真的不明白是什么错误,我也尝试了以下

$userInfo.proxyAddresses -split "-" | foreach{
            Write-Host $_
            Set-ADUser $foundUser.sAMAccountName -add @{proxyAddresses = $_}
         }

返回的错误类型无效

brccelvz

brccelvz1#

让我们尝试单独应用-split操作,看看这里实际发生了什么:

PS ~> $proxyAddresses = "smtp:jdoe@local.grp-SMTP:jdoe@local.com-"
PS ~> $proxyAddresses -split '-' |ForEach-Object { Write-Host "Got substring '$_'" }
Got substring 'smtp:jdoe@local.grp'
Got substring 'SMTP:jdoe@local.com'
Got substring ''

啊哈!结尾的-意味着-split操作返回一个数组,其中最后一项只是一个 * 空字符串 * -这可能是Set-ADUser抱怨的!
你可以过滤掉空字符串:

$proxyToAdd = $userInfo.proxyAddresses -split "-" |Where-Object { $_ }

或者你可以使用the String.Split() method,因为它可以丢弃空结果:

$proxyToAdd = $userInfo.proxyAddresses.Split("-", [StringSplitOptions]::RemoveEmptyEntries)

相关问题