AD_NewUser参数Powershell错误

时间:2017-05-23 14:13:58

标签: powershell

我正在尝试自动创建新的AD用户。下面是一段违规代码;

    New-ADUser -GivenName "$firstname" `
-Surname $surname -DisplayName ($firstname + ' ' + $surname)  `
-UserPrincipalName ($firstname + '.' + $surname + $email) -EmailAddress ($firstname + '.' + $surname + $email) -Department $department -HomePhone $phonenumber -AccountPassword $plainpassword  -ChangePasswordAtLogon 1 -Enabled 1 -Fax "OMITTED" -HomeDirectory "OMITTED" + $firstname + "." + $surname "\My Documents" -HomeDrive "M:" -Manager $manager -OtherAttributes @{'title'=$jobtitle}

当我输入$ firstname作为Owen时,我收到以下错误;

    New-ADUser : A positional parameter cannot be found that accepts argument 'Owen'.
At C:\Users\ryan.hargreavesadmin\Desktop\NewUser.ps1:24 char:1
+ New-ADUser -GivenName $firstname `
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidArgument: (:) [New-ADUser], ParameterBindingException
    + FullyQualifiedErrorId : PositionalParameterNotFound,Microsoft.ActiveDirectory.Management.Commands.NewADUs 
   er

我可能遗失哪些明显的东西?

2 个答案:

答案 0 :(得分:0)

尝试双重引用给定的变量 像这样:

$firstname = Read-Host 'Enter first name'
New-ADUser -GivenName "$firstname" ` #Script continues for other parameters

答案 1 :(得分:0)

您的问题将是您传递给参数的值之一的空格。空格之前的子字符串用作参数的值,并且没有另一个参数来定义剩下的内容。

一个例子是-HomeDirectory John Owen + $firstname + "." + $surname "\My Documents"这里HomeDirectory的值只是John,其余的将尝试使用位置来填充下一个参数。

如果将参数值括在双引号中并依赖于变量插值而不是使用+运算符构建字符串,则更容易避免这些问题,因为整个值将始终传递给参数。

通过示例,它看起来像:-HomeDirectory "John Owen$firstname.$surname\My Documents"

将此应用于您的所有代码将如下所示:

New-ADUser -GivenName "$firstname" `
-Surname $surname -DisplayName "$firstname $surname"  `
-UserPrincipalName "$firstname.$surname$email" `
-EmailAddress "$firstname.$surname$email"
-Department $department `
-HomePhone $phonenumber `
-AccountPassword $plainpassword `
-ChangePasswordAtLogon 1 `
-Enabled 1 `
-Fax "OMITTED" `
-HomeDirectory "OMITTED$firstname.$surname\My Documents" `
-HomeDrive "M:" `
-Manager $manager `
-OtherAttributes @{'title'=$jobtitle}