电子邮件 Power-shell 脚本。

电子邮件 Power-shell 脚本。

我希望我编写的这个脚本能够将其输出通过电子邮件发送,并在控制台中显示输出。我已经编写了它,但它似乎没有按预期工作。

我怎样才能创建这封电子邮件?

Clear
$serverlist = Get-Content -Path c:\Users\jasonbe\Serverlist.txt
$Path = "\z$\Backups\daily\Daily_Year2012Month7Day1.bkf"

#Email#
$smtp = "mailserverhost" 
$to = "[email protected]" 
$from = "[email protected]" 
$sub = "Server Status" 
$body = @"
"@

foreach ($server in $serverlist) 
{if ((Test-Path "\\$server\$Path") -eq $False)
    {write-host -ForegroundColor Red "$server needs backup"}
elseif ((Test-Path "\\$Server\$Path") -eq $True)
{write-host -ForegroundColor blue "$server has backup"}}

$body   
send-MailMessage -SmtpServer $smtp -To $to -Subject $sub -Body $body  -From $from

答案1

修复了脚本中的多个错误以获得可正常运行的脚本:

Clear
$serverlist = Get-Content -Path c:\Users\jasonbe\Serverlist.txt
$bkf = "Daily_Year$(date -F yyyy)Month$(date -F MM)Day$(date -F dd).bkf" <# Added dynamic date variable so it doesn't have to be updated manually each time #>
$Path = "z$\Backups\daily\$bkf" <# removed beginning '\' since it will screw up the Test-Path check below #>

[array]$array = $null <# declare a null array that we add data to later (also resets the variable to null if running multiple times) #>

foreach ($server in $serverlist) {
    if ((Test-Path \\$server\$Path) -eq $False) { <# no need to quote the path #>
        write-host -ForegroundColor Red "$server needs backup"
        $array += "$server needs backup" <# added update to $array variable #>
        }
    else { <#if ((Test-Path "\\$($Server)\$Path") -eq $True)#> <# no need to check for this since it must be True at this point in the script #>
        write-host -ForegroundColor blue "$server has backup"
        $array += "$server has backup" <# added update to $array variable #>
        }
    }
$EmailBody = ForEach ($row in $array) {"`r`n",$row} <# puts each addition to the $body variable on its own line in the e-mail, otherwise they will all run together.#>
#Email#
$messageParameters = @{ <# put all e-mail variables in another variable to simplify send-MailMessage command #>
SmtpServer = "mailserverhost" 
To = "[email protected]" 
From = "[email protected]" 
Subject = "Server Status"
Body = "$($Emailbody)"
}

send-MailMessage @messageParameters

相关内容