出现 Splatting 错误的 New-ADUser

出现 Splatting 错误的 New-ADUser

尝试运行以下代码片段时出现错误。

$Users = Import-Csv -Path $Path            
foreach ($User in $Users)            
{
    $Domain = "Domain.lan"
    $DefaultPassword = 'Password123'
    $Parms = @{'Name'= "$($User.Lastname), $($User.Firstname) $($User.middleinitial)";
               'DisplayName' = "$($User.Firstname) $($User.Middleinitial) $($User.LastName)";
               'samAccountName' = "$($User.Firstname[0])$($User.middleinitial)$($User.Lastname)".ToLower();
               'UserPrincipalName' = "$($User.Firstname[0])$($User.middleinitial)$($User.Lastname)@domain.lan".ToLower();
               'GivenName' = $User.Firstname;
               'Surname' = $User.LastName;
               'Initials' = $User.middleinitial;
               'EmailAddress' = $User.EmailAddress;
               'AccountPassword' = (ConvertTo-SecureString $DefaultPassword -AsPlainText -Force);
               'Enabled' = $true;
               'Path' = "OU=Users,DC=domain,DC=lan";
               'ChangePasswordAtLogon' = $True;
               'PasswordNeverExpires' = $false
        }

    if (Get-ADObject -Filter { samAccountName -eq "$($Parms.samAccountName)"})
    {
        Write-Error "The user $($Parms.SAMAccountName) is already a user in $Domain"
    }
    else
    {
        $Account = New-ADUser $Parms -PassThru
    }

我收到的错误是:

New-ADUser : The name provided is not a properly formed account name
At C:\Tools\Scripts\Add-BatchUsers.ps1:34 char:9
+         New-ADUser $Parms
+         ~~~~~~~~~~~~~~~~~
+ CategoryInfo          : NotSpecified: (CN=System.Colle...DC=Domain,DC=lan:String) [New-ADUser], ADException
+ FullyQualifiedErrorId : ActiveDirectoryServer:1315,Microsoft.ActiveDirectory.Management.Commands.NewADUser

但是,如果我使用相同的 $Parms 指定每个参数,命令将按预期工作。有人能解释这种行为吗?

答案1

@Params当你 splat 时,你必须像在调用站点那样表达变量,而不是$Params

相关内容