首页 > 解决方案 > PowerShell - 每 1 分钟循环一次

问题描述

我有一个查询 AD 的脚本,如果它找到在 24 小时内创建的用户,它将通过电子邮件发送给他们。我的这部分工作正常,但我似乎无法弄清楚为什么 1)它在 PowerShell 窗口中逐行工作,但没有运行与 .ps1 文件完全相同的代码;2) 为什么 $mailBody 中的 $name 字段根本不显示。它显示 $username 但不显示 $name。我将在代码下方发布错误消息。

clear
Import-Module ActiveDirectory
$secpasswd = ConvertTo-SecureString "xxxx" -AsPlainText -Force
$mycreds = New-Object System.Management.Automation.PSCredential ("xxx@xxx.com", $secpasswd)
$PSEmailServer = "xxx@xxx.com"
$SMTPPort = 587
$SMTPUsername = "xxx@xxx.com"
$MailFrom = "xxx@xxx.com"
$MailSubject = "Your user account has been created"

#Pull users created within last 24 hours

$when =  ((get-date).AddDays(-2)).addMinutes(-0) #past 24 hours from current time
$when
$users = Get-ADUser -Filter {whenCreated -ge $when} -Properties whenCreated,mail,givenname,surname,SAMAccountName,info | Select-Object whenCreated,mail,givenname,surname,SAMAccountName,info | where info -ne true

Foreach ($user in $users) 
{
$users
$name = $user.name
$emailTo = $user.mail
$username = $user.SAMAccountName
$MailBody =" <p>Dear $name,
Your CDAT Account has been created. <br><br>
Your Username is $username <br><br>
Please contact CDAT support for further assistance. <br><br>
CDAT Support Team <br><br>

This email was auto-generated. Please do not reply. If you need assistance, please contact CDAT Support. <br><br>
Confidentiality Notice: This email message, including any attachments, is for the sole use of the intended recipient(s), and may contain confidential and privileged information. Any unauthorized review, use, disclosure, or distribution is prohibited. If you are not the intended recipient, please contact the sender by reply email and destroy all copies of the original message.<br><br>
</P>"
    Send-MailMessage -From $MailFrom -To $emailTo -Subject $MailSubject -Body $MailBody -BodyAsHtml -Port $SMTPPort -UseSsl -Credential $mycreds
    Set-AdUser -identity $username –replace @{info=”true”}


}

"PS C:\scripts> .\EmailUsers24HoursAfterAccountCreation.ps1
At C:\scripts\EmailUsers24HoursAfterAccountCreation.ps1:33 char:36
+         Set-AdUser -identity $username –replace @{info=â€trueâ€}
+                                          ~~~~~~~~~~~~~~~~~~~~~~~~~~~
The string is missing the terminator: ".
At C:\scripts\EmailUsers24HoursAfterAccountCreation.ps1:18 char:2
+     {
+     ~
Missing closing '}' in statement block or type definition.
    + CategoryInfo          : ParserError: (:) [], ParseException
    + FullyQualifiedErrorId : TerminatorExpectedAtEndOfString"

标签: powershell

解决方案


推荐阅读