我无法使用于从csv创建用户并通过电子邮件将密码发送给我的脚本工作,有什么想法吗?



我正在尝试创建一个脚本,将读取一个CSV充满用户创建。然后它将创建用户并生成随机密码,然后需要向我发送一封电子邮件,其中包含所有创建的用户和所有相应的密码以及原始CSV。我当前的脚本不能正常工作,问题如下所述。

脚本目前不能很好地工作。CSV中有五个测试用户,它所能做的就是创建第一个用户,但没有正确完成。没有名字或显示名。它也不是在set组中创建的,并且是禁用的。然后它用CSV发送邮件但不给我它创建的用户,它只给我所有的错误。我有一种感觉,如果这确实有效,它将为每个用户创建使用相同的密码,它需要是唯一的。

$filePath = “D:myfilepathScriptTestUsers.csv”
# Import the CSV file containing the user information
$users = Import-Csv $filePath
# Create an empty array to store the created users with their passwords
$createdUsers = @()
# Create an empty array to store the users that couldn't be created and the errors
$errorUsers = @()
# Loop through each user in the CSV file
foreach ($user in $users) {
$firstname = $user.'FirstName' # Get the firstname from the CSV file
$lastname = $user.'LastName' # Get the lastname from the CSV file
$username = $user.'UserName' # Get the username from the CSV file
# Check if the 'UserName' field is empty, if so, add the user to the error array and continue to the next iteration
if (!$username) {
$error = "Missing 'UserName' field for a user in the CSV file, skipping."
$errorUsers += "$username $error"
continue
}
# Check if the user already exists in AD, if so, add the user to the error array and continue to the next iteration
if (Get-ADUser -Identity $username -ErrorAction SilentlyContinue) {
$error = "User $username already exists in AD, skipping."
$errorUsers += "$username $error"
continue
}
$ou = $user.'OU' # Get the OU from the CSV file
# Check if the specified OU exists, if not, add the user to the error array and continue to the next iteration
if (!(Get-ADOrganizationalUnit -Identity $ou -ErrorAction SilentlyContinue)) {
$error = "OU $ou does not exist, skipping."
$errorUsers += "$username $error"
continue
}
$groups = $user.'Groups' # Get the groups from the CSV file
# Check if the specified group(s) exists, if not, add the user to the error array and continue to the next iteration
if ($groups) {
$missingGroups = $groups | Where-Object { !(Get-ADGroup -Identity $_ -ErrorAction SilentlyContinue) }
if ($missingGroups) {
$error = "Group(s) $missingGroups do not exist, skipping."
$errorUsers += "$username $error"
continue
}
}
$expiry = $user.'ExpiryDate' # Get the account expiry date from the CSV file
$description = $user.'Description' # Get the description from the CSV file
# Generate a random password
$password = [System.Web.Security.Membership]::GeneratePassword(16, 2)
#$email = "<myemail@email.com>"
# Create the AD user and add them to the specified groups
try {
New-ADUser -Name $firstname -Surname $lastname -SamAccountName $username -UserPrincipalName $username -Path $ou -Description $description -AccountExpirationDate $expiry -PassThru | Set-ADAccountPassword -Reset -NewPassword (ConvertTo-SecureString $password -AsPlainText -Force)
if ($groups) {
Add-ADGroupMember -Identity $groups -Members $username -ErrorAction Stop
}
# Add the user and their password to the array of created users
$createdUsers += "$username $password"
} catch {
$error = $_.Exception.Message       
$errorUsers += "$username $error"
}
}

# Create the HTML body of the email with CSS styling
$body = "<html><head><style>body { background-color: lightblue; font-family: calibri;}</style></head><body>Successfully Created Users:<br>" + ($createdUsers -join "<br>") + "<br><br>Users that couldn't be created and the errors:<br>" + ($errorUsers -join "<br>") + "</body></html>"
# Send the email with the list of created users and their passwords and attach the original CSV file

$DateSh = (Get-Date).ToString("yyyyMMdd")
#Email options
$options = @{
'SmtpServer' = "relay" 
'To' = "<myemail@email.com>"
'From' = "SERVER1 <server1@domain>" 
'Subject' = "$DateSh-NewUsersCreated" 
'BodyAsHtml' = $true
'Attachments' = $filePath  
}
#Send email
Send-MailMessage @options -Body $Body

运行后收到的错误如下:

Get-ADUser: Cannot find object with identity: 'ScriptTestUser001' under: 'DC=mydc'

Get-ADGroup: Cannot find a object with identity: 'Group1, Group2' under: 'DC=mydc'

不能覆盖变量Error,因为它是只读或常量。

请帮助。

查看用户是否存在,可以使用:

$userFound = $true
try {
Get-ADUser -Identity $username -ErrorAction Stop
}
catch {
$userFound = $false
}
if($userFound) {
$errorText = "User $username already exists in AD, skipping."
$errorUsers += "$username $errorText"
continue
}

对于组,您不能只传递一个字符串,所有组之间用逗号和空格分隔,您需要首先将其拆分为一个数组:

$groups = $user.'Groups' -split ', '
$missingGroups = @()
foreach($group in $groups)
{
try {
Get-ADGroup -Identity $group -ErrorAction Stop
}
catch {
$missingGroups += $group
}    
}
if($missingGroups.Length -ne 0)
{
$errorText = "Group(s) $($missingGroups -join ',') do not exist, skipping."
$errorUsers += "$username $errorText"
continue
}

关于帐户在创建后被禁用,这是正常的,您在创建用户时没有提供密码(这里有记录)

try {
New-ADUser -Name $firstname -Surname $lastname -SamAccountName $username -UserPrincipalName $username -Path $ou -Description $description -AccountExpirationDate $expiry -AccountPassword (ConvertTo-SecureString $password -AsPlainText -Force)
foreach($group in $groups) {
Add-ADGroupMember -Identity $group -Members $username -ErrorAction Stop
}
...

是的,正如@vonPryz所提到的,$Error变量是保留的(这在这里有记录)。

最新更新