PowerShell发送电子邮件

时间:2015-04-09 16:47:56

标签: powershell powershell-v4.0

我正在运行一个任务计划程序,每30分钟执行一次PowerShell。

所以

  

$ users = Search-ADAccount -LockedOut -SearchBase   “OU = People,DC = Example,DC = com”-SearchScope Subtree |选择   Sam帐户

返回用户列表。现在我想创建一个包含用户的电子邮件主体

$EmailBody = ForEach($user in $users) {"`r`n",$user}



Send-MailMessage -To $to -Subject "Locked Accounts" -BodyAsHtml $EmailBody -From $from -Credential $cred -SmtpServer $server -Debug

但即使没有锁定,我的当前代码也会发送电子邮件。无论如何我可以查看$ users是否至少有1个人?

(我没有测试过$ EmailBody但是想知道BodyAsHtml是否可以接受这个)

=====

更新代码

if ($users)    {
    if ($users.count -gt 0) {#even if there are users, this line always is false. 
        # send the email here
        foreach($user in $users)
        {
            $message = $message + " " + $user + " is locked out" + "`r`n"
            Write-Host $user
        }
        Send-MailMessage -To $to -Subject "Locked Accounts" -BodyAsHtml $message -From $from -Credential $cred -SmtpServer $server -Debug        
    } }

1 个答案:

答案 0 :(得分:0)

if ($users -ne $null)   # lists can be empty as well, in which case the count fails
{
    if ($users.count -gt 0) {
        # send the email here
    }
}