用于将新用户从 CSV 文件添加到 Active Directory 的 Powershell 脚本无法运行。该错误表明语法错误,但我不明白为什么

Powershell script to add new users to Active Directory from a CSV file fails to work. The error suggests bad syntax but I am failing to see why

我编写了一个 Powershell 脚本,用于将新用户从 CSV 文件添加到 Active Directory。当我 运行 脚本时,我在代码的 New-ADuser 部分遇到错误的语法错误。我看不出语法怎么会错。我的代码编辑器也没有选择任何东西。我已附上错误消息和 CSV 文件的屏幕截图。

# Import Active Directory module
Import-Module ActiveDirectory
 
# Open file dialog
# Load Windows Forms
[System.Reflection.Assembly]::LoadWithPartialName("System.windows.forms") | Out-Null
 
# Create and show open file dialog
$dialog = New-Object System.Windows.Forms.OpenFileDialog
$dialog.InitialDirectory = $StartDir
$dialog.Filter = "CSV (*.csv)| *.csv" 
$dialog.ShowDialog() | Out-Null
 
# Get file path
$CSVFile = $dialog.FileName
 
# Import file into variable
# Lets make sure the file path was valid
# If the file path is not valid, then exit the script
if ([System.IO.File]::Exists($CSVFile)) {
    Write-Host "Importing CSV..."
    $CSV = Import-Csv -LiteralPath "$CSVFile"
} else {
    Write-Host "File path specified was not valid"
    Exit
}
 
# Lets iterate over each line in the CSV file
foreach($user in $CSV) {
 
    # Password
    $SecurePassword = ConvertTo-SecureString "$($user.'First Name'[0])$($user.'Last Name')$($user.'Employee ID')!@#" -AsPlainText -Force

 
    # Create new user
    New-ADUser -Name $user.'Full Name' `
                -GivenName $user.'First Name' `
                -Surname $user.'Last Name' `
                -EmailAddress $user.'Email Address' `
                -DisplayName $user.'Full Name' `
                -Path "$($user.'Organizational Unit')" `
                -ChangePasswordAtLogon $true `
                -AccountPassword $SecurePassword `
                -Enabled $([System.Convert]::ToBoolean($user.Enabled))
 
    # Write to host that we created a new user
    Write-Host "Created $Username / $($user.'Email Address')"
 
    # If groups is not null... then iterate over groups (if any were specified) and add user to groups
    if ($User.'Add Groups (csv)' -ne "") {
        $User.'Add Groups (csv)'.Split(",") | ForEach {
            Add-ADGroupMember -Identity $_ -Members "$($user.'First Name').$($user.'Last Name')"
            WriteHost "Added $Username to $_ group" # Log to console
        }
    }
 
    # Write to host that we created the user
    Write-Host "Created user $Username with groups $($User.'Add Groups (csv)')"
}
 
Read-Host -Prompt "Script complete... Press enter to exit."

看看这个

你是说

DC=co

此外,您确实需要研究展开和错误检查。迭代失败后,您正在向主机写入成功消息。

splatting

try/catch error checking