我已经完成了一个脚本来检查UPS状态,记录它并发送通知电子邮件。如果手动运行脚本可以正常工作,但通过任务计划程序执行时,它不会发送电子邮件。它会做其他所有事情(例如它正确记录到文件中),所以我不明白发生了什么。
任何提示和/或解释?非常感谢!
这是脚本:
<#
.SYNOPSIS
Skript pro test stavu napájení (AC, nebo UPS)
.DESCRIPTION
Zjistí stav napájení, a pokud to není AC, ale baterie, pole notifikační e-mail. Stejně tak ho pole, pokud ádná baterie připojena není.
.PARAMETER none
no parameters
.EXAMPLE
no example needed
.NOTES
crysman (copyleft) 2016
# changelog:
# ... next version - don't forget to update the $scriptVersion variable!
# 2016-03-10 přidány barvy výstupů, help, upraveny exit codes a návratové hodnoty, upraven hostname
# 2016-03-09 opraveno logování, vč. loggingu nefunkčních mailnotifikací
# 2016-03-08 initial release
#>
$scriptVersion = '2016-03-10'
$scriptName = $MyInvocation.mycommand.name
$timestamp = [datetime]::now.tostring("yyyy-MM-dd_HH-mm")
$hostName = [system.environment]::MachineName.ToLower()
#funkce pro posílání notifikačních mailů
#v.1.2
function sendEmail($Subject, $Body){
$EmailTo = "it@XXXYOURFAVOURITEDOMAIN.cz"
$EmailFrom = "$global:hostName@XXXYOURFAVOURITEDOMAIN.cz"
$SMTPServer = "smtp.XXXYOURFAVOURITEDOMAIN.cz"
$SMTPClient = New-Object Net.Mail.SmtpClient($SMTPServer, 587)
$SMTPClient.EnableSsl = $true
$SMTPClient.Credentials = New-Object System.Net.NetworkCredential("notifications@XXXYOURFAVOURITEDOMAIN.cz", "XXXYOURFAVOURITEPASSWORD");
$Body = "$Body `n-----`nscript $global:scriptName v.$global:scriptVersion on host $global:hostName`ntimestamp: $global:timestamp"
#Write-Host $EmailTo $EmailFrom $Subject $Body
try {
$SMTPClient.Send([string]$EmailFrom,[string]$EmailTo,[string]$Subject,[string]$Body)
}
catch {
$msg = "$global:timestamp WARNING: notification e-mail has NOT been sent, please check SMTP credentials"
Write-Host "ERR: " $Error[0].ToString() -ForegroundColor Red
#následující řádek nefunguje - proč? :( - do souboru se zapisuje, ale na screen ne!
#Write-Output $msg | Tee -Append -FilePath $global:errorLog
Write-Host $msg -ForegroundColor Red
Write-Output $msg | Out-File -Append $global:errorLog
return $false
}
finally {
$SMTPClient.Dispose()
}
Write-Host "notification e-mail has been sent succesfully" -ForegroundColor Gray
return $true
}
$scriptDir = "D:\scripts"
$log = "$scriptDir\checkPowerUPS-error.log"
$errorLog = $log
# kategorie stavů baterie viz https://msdn.microsoft.com/en-us/library/aa394074(v=vs.85).aspx
$bStats= @{"1"="battery is discharging";"2"="On AC";"3"="Fully Charged";"4"="Low";"5"="Critical";"6"="Charging";"7"="Charging and High";"8"="Charging and Low";"9"="Charging and Critical";"10"="Undefined";"11"="Partially Charged";}
# aktuální stav:
$powerStat=Get-WmiObject -class Win32_Battery -ComputerName localhost
$bStat=$powerStat.BatteryStatus
$bStatText=$bStats["$bStat"]
$bStatRemaining=$powerStat.EstimatedRunTime
#zapíeme do EventLogu, popř. poleme mail
#nachystat EventLog
$eLog = $scriptName #pouijeme název skriptu
if (! $eLog) {
Write-Output "$timestamp něco je patně s powershellem (?)" | tee -Append -FilePath $log
exit 99
}
$eLogExists = get-EventLog -LogName Application -Source "$eLog"
if (! $eLogExists){
echo "WARNING: jetě neexistuje eventlog, vytvářím..."
new-EventLog -LogName Application -Source "$eLog"
}
#zalogovat a notifikovat
if (!($powerStat) -or $bStat -eq 1 -or $bStat -eq 4 -or $bStat -eq 5) {
if(!$powerStat){
#(nemáme UPS)
$Subject = "IMPORTANT: Power without UPS on $hostName"
$Body = "this host seems NOT to be connected to any battery/UPS"
} else {
#(UPS máme, ale nějaký non-AC status)
$Subject = "IMPORTANT: Power failure on $hostName"
$Body = "battery status is $bStat ($bStatText), estimated remaining battery time: $bStatRemaining min"
}
#vypsat na screen a zalogovat:
Write-Output "$timestamp $Body" | Out-File -Append $log
Write-Host "$timestamp $Body" -ForegroundColor Red
Write-EventLog -LogName Application -Source "$eLog" -EntryType Warning -EventId 11 -Message "$eLog skončil neúspěně - $Body"
#poslat maila:
$mailsent = sendEmail $Subject $Body
if ($mailsent) {$exitcode=1} else {$exitcode=2}
} else {
$exitcode = 0
Write-Host "OK, $hostName is on AC (status $bStat)`nscript $scriptName v.$scriptVersion" -ForegroundColor Green
}
exit $exitcode
这是任务:
<Task xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task" version="1.2">
<RegistrationInfo>
<Date>2016-03-07T16:53:24.9000439</Date>
<Author>SERVER-XXX\myadminaccount</Author>
</RegistrationInfo>
<Triggers>
<CalendarTrigger>
<Repetition>
<Interval>PT1M</Interval>
<StopAtDurationEnd>false</StopAtDurationEnd>
</Repetition>
<StartBoundary>2016-03-07T00:00:00</StartBoundary>
<Enabled>true</Enabled>
<ScheduleByDay>
<DaysInterval>1</DaysInterval>
</ScheduleByDay>
</CalendarTrigger>
</Triggers>
<Principals>
<Principal id="Author">
<UserId>SERVER-XXX\myadminaccount</UserId>
<LogonType>Password</LogonType>
<RunLevel>HighestAvailable</RunLevel>
</Principal>
</Principals>
<Settings>
<MultipleInstancesPolicy>StopExisting</MultipleInstancesPolicy>
<DisallowStartIfOnBatteries>false</DisallowStartIfOnBatteries>
<StopIfGoingOnBatteries>true</StopIfGoingOnBatteries>
<AllowHardTerminate>true</AllowHardTerminate>
<StartWhenAvailable>true</StartWhenAvailable>
<RunOnlyIfNetworkAvailable>false</RunOnlyIfNetworkAvailable>
<IdleSettings>
<StopOnIdleEnd>true</StopOnIdleEnd>
<RestartOnIdle>false</RestartOnIdle>
</IdleSettings>
<AllowStartOnDemand>true</AllowStartOnDemand>
<Enabled>true</Enabled>
<Hidden>false</Hidden>
<RunOnlyIfIdle>false</RunOnlyIfIdle>
<WakeToRun>false</WakeToRun>
<ExecutionTimeLimit>PT1H</ExecutionTimeLimit>
<Priority>7</Priority>
</Settings>
<Actions Context="Author">
<Exec>
<Command>powershell</Command>
<Arguments>
-NonInteractive -Noprofile -Command "&{D:\scripts\checkPowerUPS.ps1}"
</Arguments>
</Exec>
</Actions>
</Task>
操作系统:Windows Server 2012 R2
PS:我浏览了Technet和各种Stack Exchange网站来解决这个问题,但没有运气:/所以在这里尝试......
@doenoe因为我还没想出如何使用这个cmd-let来应用身份验证。如果你知道怎么做,请告诉我。
—
crysman 2016年
请阅读这篇 TechNet文章。有一个
—
Smeerpijp 2016年
-Credential
参数。文章中还有一个例子:send-mailmessage -to "User01 <user01@example.com>" -from "ITGroup <itdept@example.com>" -cc "User02 <user02@example.com>" -bcc "ITMgr <itmgr@example.com>" -subject "Don't forget today's meeting!" -credential domain01\admin01 -useSSL
好的,我已切换到Send-MailMessage cmd-let。然而,一切都没有改变。手动运行会执行所有操作,包括发送通知电子邮件。任务计划程序报告退出代码0,一切似乎都很好,文件日志中有新行,系统事件查看器中有新日志,但没有发送电子邮件!:(
—
crysman 2016年
嗯,我有一个运行PS脚本的sched任务,并在完成后发送邮件,这是我在action标签程序脚本中的任务参数:
—
Smeerpijp 2016年
C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe
参数: -command "& 'C:\Scripts\asabackup\asabackup.ps1'"
开始:C:\Scripts\asabackup
也许你可以调整你的值来匹配我的(与你自己的工作目录等)并再次测试
.NET SmtpClient
该类发送电子邮件而不是本机Send-Mailmessage
cmd-let?