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

PowerShell Core中使用[wmiclass]实现WMI事件订阅无法正常运行问题求助

问题排查与修复方案
  • 未定义变量问题:你的代码中使用了未赋值的$sourceIdentifier变量给事件过滤器的Name属性赋值,这会直接导致过滤器创建异常,订阅规则无法生效。
  • 消费者属性缺失:从Windows 10 1709版本开始,CommandLineEventConsumer强制要求填写ExecutablePath属性,仅配置CommandLineTemplate不会触发执行逻辑。
  • 会话隔离问题:WMI永久事件订阅默认运行在系统会话0中,启动的进程不会显示在当前用户桌面,会被误认为未启动,需要配置RunInteractively属性为$true才能显示进程窗口。
  • 权限要求:创建WMI永久订阅必须以本地管理员身份运行PowerShell,否则配置过程会静默失败或者抛出权限错误。
  • 路径重定向问题:如果你使用的是32位PowerShell,访问C:\Windows\System32会被自动重定向到SysWOW64,建议使用C:\Windows\notepad.exe作为测试路径避免重定向干扰。

修正后可运行代码

# 提前定义过滤器名称变量
$sourceIdentifier = "RegeditProcessMonitorFilter"

# 创建事件过滤器
$instanceFilter = ([wmiclass]"\\.\root\subscription:__EventFilter").CreateInstance()
$instanceFilter.QueryLanguage = "WQL"
$instanceFilter.Query = "SELECT * FROM __InstanceCreationEvent WITHIN 3 WHERE TargetInstance ISA 'Win32_Process' AND TargetInstance.Name='regedit.exe'"
$instanceFilter.Name = $sourceIdentifier
$instanceFilter.EventNamespace = 'root\cimv2'
$result = $instanceFilter.Put()
$newFilter = $result.Path

# 创建命令行事件消费者
$instanceConsumer = ([wmiclass]"\\.\root\subscription:CommandLineEventConsumer").CreateInstance()
$instanceConsumer.Name = 'RegeditMonitorConsumer'
$instanceConsumer.CommandLineTemplate = "C:\Windows\System32\notepad.exe"
# 新增必填的ExecutablePath属性
$instanceConsumer.ExecutablePath = "C:\Windows\System32\notepad.exe"
# 配置交互属性,让进程显示在当前用户桌面
$instanceConsumer.RunInteractively = $true
$result = $instanceConsumer.Put()
$newConsumer = $result.Path

# 绑定过滤器和消费者
$instanceBinding = ([wmiclass]"\\.\root\subscription:__FilterToConsumerBinding").CreateInstance()
$instanceBinding.Filter = $newFilter 
$instanceBinding.Consumer = $newConsumer
$result = $instanceBinding.Put()
$newBinding = $result.Path

<# 清理订阅的代码,测试完成后执行
([wmi]$newFilter).Delete()
([wmi]$newConsumer).Delete()
([wmi]$newBinding).Delete()
#>

测试说明

运行代码后打开注册表编辑器regedit.exe,最多等待3秒即可看到自动弹出的记事本窗口。如果不需要该订阅规则,记得执行注释中的清理代码删除残留的WMI订阅。

内容的提问来源于stack exchange,提问作者Louis Lenders

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 10:06:03