如何让PowerShell脚本运行出错时向我发送通知?
解决PowerShell脚本运行日志记录与通知问题
一、将控制台日志保存到文本文件
有两种可靠的方式实现日志留存:
1. 使用Start-Transcript捕获全量输出
这是PowerShell内置的日志工具,能完整记录脚本运行的所有控制台输出(包括错误信息),推荐优先使用。在脚本首尾添加以下代码:
# 定义日志路径,按日期命名避免覆盖,可自行修改路径 $logPath = "D:\ScriptLogs\DailyTask_$(Get-Date -Format 'yyyyMMdd').log" # 启动日志记录,-Append参数可选,需要追加到同文件时添加 Start-Transcript -Path $logPath -IncludeInvocationHeader # --- 你的原有脚本内容 --- # 停止日志记录 Stop-Transcript
2. 重定向脚本输出到文件
若只需捕获特定输出或错误,可在Task Scheduler中配置重定向,或在脚本内直接设置:
# 脚本内将所有输出(含错误)写入日志文件 & "D:\YourScripts\DailyTask.ps1" *> "D:\ScriptLogs\DailyTask_$(Get-Date -Format 'yyyyMMdd').log"
也可在Task Scheduler的「操作」→「编辑操作」中,将「添加参数」设为:
-File "D:\YourScripts\DailyTask.ps1" *> "D:\ScriptLogs\DailyTask_$(Get-Date -Format 'yyyyMMdd').log"
二、发送包含日志的邮件通知
如果需要实时掌握脚本运行状态,可在脚本完成后(或捕获错误时)发送邮件:
1. 无论成功失败都发送日志邮件
脚本结束后读取日志内容,作为邮件正文发送:
# 日志文件路径需与前面日志记录的路径一致 $logPath = "D:\ScriptLogs\DailyTask_$(Get-Date -Format 'yyyyMMdd').log" $logContent = Get-Content $logPath -Raw # 邮件基础配置,替换为公司实际信息 $smtpServer = "smtp.yourcompany.com" $smtpPort = 587 $fromAddress = "script-notify@yourcompany.com" $toAddress = "your-email@yourcompany.com" $subject = "每日任务脚本运行日志 - $(Get-Date -Format 'yyyy-MM-dd')" # 发送邮件,需SSL则保留-UseSsl参数 Send-MailMessage -SmtpServer $smtpServer -Port $smtpPort ` -From $fromAddress -To $toAddress ` -Subject $subject -Body $logContent ` -UseSsl
2. 仅在脚本出错时发送通知
通过try/catch块监控脚本执行,捕获错误后发送告警:
$logPath = "D:\ScriptLogs\DailyTask_$(Get-Date -Format 'yyyyMMdd').log" Start-Transcript -Path $logPath -IncludeInvocationHeader try { # --- 你的原有脚本内容 --- if ($Error.Count -gt 0) { throw "脚本执行出现异常" } } catch { $errorContent = Get-Content $logPath -Raw $smtpServer = "smtp.yourcompany.com" $fromAddress = "script-notify@yourcompany.com" $toAddress = "your-email@yourcompany.com" $subject = "⚠️ 每日任务脚本运行失败 - $(Get-Date -Format 'yyyy-MM-dd')" Send-MailMessage -SmtpServer $smtpServer -From $fromAddress -To $toAddress ` -Subject $subject -Body $errorContent -UseSsl } finally { Stop-Transcript }
三、Task Scheduler关键配置注意事项
- 确保运行脚本的账户拥有日志目录的读写权限,以及访问公司SMTP服务器的权限;
- 在「常规」选项卡勾选「不管用户是否登录都运行」,避免因账户未登录导致脚本不执行;
- 若脚本需访问系统敏感资源,可勾选「以最高权限运行」;
- 检查「操作」中的「程序或脚本」是否为
powershell.exe,参数配置需准确(如指定脚本路径、日志重定向规则)。
内容的提问来源于stack exchange,提问作者lwcjake
相关产品推荐
相关产品推荐

