[英]Powershell CSV Import Error - The object name has bad syntax
似乎無法找出導致“ 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
}
}
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。 Get-ADOrganizationalUnit
的Identity
參數必須是以下之一:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.