我使用以下 PowerShell 脚本创建新的 AD 用户,创建用户后,Powershell 中将显示用户 ID 和密码。现在,我希望将此用户 ID 和密码自动发送给新用户,并附上一个 pdf 附件,说明如何使用 SMTP 服务器重置密码。
# Import active directory module for running AD cmdlets
Import-Module activedirectory
#Store the data from user.csv in the $user variable
$ADUsers = Import-csv d:useraccount\user.csv
#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
$FirstName = $User.FirstName
$Initials = $User.Initials
$Surname = $User.LastName
$DisplayName = $User.DisplayName
$Path = $User.Path
$SamAccountName = $User.SamAccountName
$Password = $User.Password
$Description = $User.Description
if (Get-ADUser -F {SamAccountName -eq $SamAccountName})
{
#If user does exist, give a warning
Write-Warning "A user account with Logon Name $SamAccountName 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 $SamAccountName `
-UserPrincipalName "$SamAccountName@DCNAME" `
-Name "$Firstname $Lastname" `
-GivenName $Firstname `
-Surname $Lastname `
-Initials $Initials `
-DisplayName $DisplayName `
-Description $Description `
-AccountPassword (convertto-securestring $Password -AsPlainText -Force) -ChangePasswordAtLogon $True
add-adgroupmember $MemberGroup $SamAccountName
}
}
我的问题是,有人有示例脚本可以供我参考来完成此任务吗?我已经安装并配置了 SMTP,但不太清楚如何添加脚本以在创建新用户时触发电子邮件。
答案1
PowerShell 内置了对发送 SMTP 消息的支持:https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.utility/send-mailmessage。
基本语法:
Send-MailMessage -From 'User01 <[email protected]>' -To 'User02 <[email protected]>' -Subject 'Test mail'
更详细的示例(取自同一篇文章),其中还包括附件和要使用的邮件服务器:
Send-MailMessage -From 'User01 <[email protected]>' -To 'User02 <[email protected]>' -Subject 'Sending the Attachment' -Body "Forgot to send the attachment. Sending now." -Attachments .\data.csv -SmtpServer 'smtp.fabrikam.com'
顺便说一句,您不需要安装 SMTP 服务器来发送电子邮件,并且除非您正确配置它和其他一些功能(例如 SPF),否则它可能无法工作;使用现有的服务器要容易得多。