我编写了一个脚本来检查 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 = "[email protected]"
$EmailFrom = "$global:[email protected]"
$SMTPServer = "smtp.XXXYOURFAVOURITEDOMAIN.cz"
$SMTPClient = New-Object Net.Mail.SmtpClient($SMTPServer, 587)
$SMTPClient.EnableSsl = $true
$SMTPClient.Credentials = New-Object System.Net.NetworkCredential("[email protected]", "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
附言:我浏览过 Technet 和各种 Stack Exchange 网站来解决这个问题,但没有成功 :/ 所以在这里尝试...
答案1
经过几个小时的调试,我终于明白了。
问题:
任务计划程序中参数的使用-Command "..."
。
解决方案:
改用-File "..."
参数。在这个特定情况下,参数应该是:
<Exec>
<Command>powershell</Command>
<Arguments>
-NonInteractive -Noprofile -File "D:\scripts\checkPowerUPS.ps1"
</Arguments>
</Exec>
细节:
当使用时-Command "&{D:\testScript.ps1}"
,脚本中声明的全局变量不可用,即例如这将不起作用:
$myVar = "ham"
function myF(){
Write-Output $global:myVar
}
myF
我还没有找到解决以下问题的答案:-Command
“和-File
PowerShell 参数有什么区别?”无论如何,调用powershell /?
对我没有帮助,因为它没有提到全局和/或任何“半全局”变量。此外,它指出使用-Command
:
...执行指定的命令(和任何参数),就像在 Windows PowerShell 命令提示符下键入一样......
事实并非如此,因为启动一个新的 PowerShell 窗口并使用 $myVar 执行我在上面的示例代码中输入的行将起作用,而执行使用该示例则-Command ...
不会起作用。
我希望这能帮到您。