PowerShell脚本执行Write-EventLog后无法继续执行问题求助
PowerShell脚本写入事件日志后停止运行的解决方法
问题描述
编写了一段PowerShell脚本用于监听日志文件,匹配到指定关键词时执行后续操作。脚本内容如下:
$keywords=Get-Content "C:\Users\user\desktop\keywords.txt" Get-Content "C:\Users\user\desktop\some.log" -tail 1 -wait | ForEach-object { foreach($word in $keywords) { if($_ -match "$word") { Write-EventLog -LogName Application -EventID 2001 -EntryType Information -Source serviceCheck -Message "[SUCCESS] The service has been initialized" Write-Host "[SUCCESS] The service has been initialized" } } } | Select -First 1
目前脚本可正常写入事件日志,但执行Write-EventLog后无法继续运行后续代码;若将if块内的命令替换为Get-Date等其他命令,脚本则能正常继续执行。
解决方案
问题出在末尾的| Select -First 1命令:
Select -First 1的作用是从管道中获取第一个对象后,立即终止整个上游管道(包括Get-Content -Wait的持续监听)。- 当执行
Write-EventLog时,若因隐性权限问题或输出逻辑产生了进入管道的对象(如错误信息),Select -First 1会触发终止逻辑,导致脚本停止监听日志;而Get-Date的输出未进入管道,因此脚本能继续运行。
只需移除末尾的| Select -First 1即可让脚本持续监听日志并在匹配关键词后继续执行:
修改后的脚本:
$keywords=Get-Content "C:\Users\user\desktop\keywords.txt" Get-Content "C:\Users\user\desktop\some.log" -tail 1 -wait | ForEach-object { foreach($word in $keywords) { if($_ -match [regex]::Escape($word)) { # 处理关键词中的正则特殊字符,避免匹配出错 Write-EventLog -LogName Application -EventID 2001 -EntryType Information -Source serviceCheck -Message "[SUCCESS] The service has been initialized" Write-Host "[SUCCESS] The service has been initialized" } } }
额外注意事项:
- 确保
serviceCheck事件日志源已存在,若不存在需以管理员权限执行New-EventLog -LogName Application -Source serviceCheck创建。
内容的提问来源于stack exchange,提问作者Delyan
相关产品推荐
相关产品推荐

