Powershell CSV导入错误-对象名称语法错误

时间:2018-08-13 08:19:05

标签: windows powershell active-directory

似乎无法找出导致“ New-ADUser”语法的脚本错误的原因。不确定是否有人可以发现错误?

“ New-ADUser:对象名称语法错误

在D:\ ScriptPath \ importadusersAndMoveOU.ps1:33 char:3“

如果删除“ $ NewOU”变量并将用户导入默认的“用户” OU中,该脚本将起作用。

# Import active directory module for running AD cmdlets
Import-Module activedirectory

#Store the data from ADUsers.csv in the $ADUsers variable
$ADUsers = Import-csv 'D:\CSVPATH\adusers.csv'
$NewOU = New-ADOrganizationalUnit -Name "ADMINS"

#Loop through each row containing user details in the CSV file 
foreach ($User in $ADUsers)
{
    #Read user data from each field in each row and assign the data to a 
variable as below


$DomainName = Get-ADDomain -current LocalComputer
$Username   = $User.username
$Password   = "TestPassword12345"
$Firstname  = $User.firstname
$Lastname   = $User.lastname
$OU         = $NewOU+","+$DomainName.DistinguishedName
$upn = $Username+"@"+$DomainName.DNSRoot

#Check to see if the user already exists in AD
if (Get-ADUser -F {SamAccountName -eq $Username})
{
     #If user does exist, give a warning
     Write-Warning "A user account with username $Username already exist in Active Directory."
}
else
{
    #User does not exist then proceed to create the new user account

    #Account will be created in the OU provided by the $OU variable read from the CSV file
    New-ADUser `
        -SamAccountName $Username `
        -UserPrincipalName $upn `
        -Name "$Firstname $Lastname" `
        -GivenName $Firstname `
        -Surname $Lastname `
        -Enabled $True `
        -DisplayName "$Lastname, $Firstname" `
        -Path $OU `
        -AccountPassword (convertto-securestring $Password -AsPlainText -Force) -ChangePasswordAtLogon $True
    Add-ADGroupMember "domain admins" $username
    Add-ADGroupMember "enterprise admins" $Username
    }
}

1 个答案:

答案 0 :(得分:1)

New-ADOrganizationalUnit -Name "ADMINS"命令在域的默认NC头下创建一个新的OU。 如果要在其他地方使用,则应使用-Path <DistinghuisedName of Parent OU>参数。

但是,正如Drew Lean所评论的那样,此代码在尝试创建OU之前不会检查OU是否存在,因此可以在此处进行快速测试:

[adsi]::Exists("LDAP://OU=ADMINS,DC=domain,DC=com")

Get-ADOrganizationalUnit -Filter "distinguishedName -eq 'OU=ADMINS,DC=domain,DC=com'"
# don't filter on 'Name' because it is more than likely you have several OUs with the same name

接下来,为变量$OU构造distinguishedName的部分将导致格式错误的字符串。 $OU = $NewOU+","+$DomainName.DistinguishedName将导致"ADMINS,DC=domain,DC=com"这不是有效的DistinghuishedName,因此错误对象名称语法错误

尝试首先获取现有OU的DN,如果不存在该DN,则在创建后将其捕获,并将DistinghuishedName存储在变量$ OU中

类似这样的东西:

$OU = "OU=ADMINS,DC=domain,DC=com"
if (-not (Get-ADOrganizationalUnit -Filter "distinguishedName -eq '$OU'")) {
    $NewOU = New-ADOrganizationalUnit -Name "ADMINS" -PassThru
    $OU = $NewOU.DistinghuishedName
}

ps。 Identity的{​​{1}}参数必须是以下之一:

  • 专有名称
  • GUID(objectGUID)
  • 安全标识符(objectSid)
  • 安全帐户管理器帐户名(sAMAccountName)