尝试使用 Powershell 批量添加 AD 用户时,对象名称语法错误

尝试使用 Powershell 批量添加 AD 用户时,对象名称语法错误

我尝试通过导入 csv 文件将一系列用户添加到 AD,但似乎无法使其成功运行,错误总是显示“对象名称语法错误”,但无论我使用何种错误处理,我都无法获得有关它的任何其他信息。

以下是脚本和 csv 的片段

# Import the PowerShell module for running AD cmdlets
Import-Module ActiveDirectory

# Store the data from your CSV file in the $ADUsers variable
$ADUsers = Import-Csv C:\NWTC-users.csv

# Read each row of input data and assign each user’s details to variables
foreach ($User in $ADUsers) {
$Firstname = $User.Firstname
$Lastname = $User.Lastname
$Username = $User.LOGINNAME
$OU = $User.OU
$Password = $User.Password

# Attempt to create the new user account in the specified OU
try {
    New-ADUser -SamAccountName $Username `
               -UserPrincipalName "[email protected]" `
               -Name "$Firstname $Lastname" `
               -GivenName $Firstname `
               -Surname $Lastname `
               -DisplayName "$Lastname, $Firstname" `
               -Enabled $True `
               -Path $OU `
               -AccountPassword (ConvertTo-SecureString $Password -AsPlainText -Force) `
               -ChangePasswordAtLogon $False  # Disable password change at next logon
    
    Write-Host "User account for $Username created successfully."

    # Create home directory
    $HomeDirectory = "\\DC\Home\$Username"
    New-Item -ItemType Directory -Path $HomeDirectory | Out-Null

    # Set permissions on home directory
    $ACL = Get-Acl $HomeDirectory
    $Permission = "SYSTEM","FullControl","ContainerInherit,ObjectInherit","None","Allow"
    $Rule = New-Object System.Security.AccessControl.FileSystemAccessRule($Permission)
    $ACL.SetAccessRule($Rule)
    Set-Acl $HomeDirectory $ACL
    
    Write-Host "Home directory for $Username created successfully."
}
catch {
    Write-Host "Failed to create user account for $Username. $_"
}

}

USERNAME,FirstName,LastName,LOGINNAME,OU,Password
RogerMcGregor,Roger,McGregor,RMCGREGOR,Business,Password1
GaleChen,Gale,Chen,GCHEN,Business,Password1

相关内容