You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.06 17:55:19