【问题标题】:Powershell WMI: Runs without any errors/exceptions, however doesn't execute scriptPowershell WMI:运行时没有任何错误/异常,但不执行脚本
【发布时间】:2015-11-01 14:32:25
【问题描述】:
$filter = ([wmiclass]"\\.\root\subscription:__EventFilter").CreateInstance()

$filter.QueryLanguage = "WQL"
$filter.Query = "Select * from __InstanceCreationEvent within 5 where targetinstance isa 'win32_logicaldisk'"
$filter.Name = "USBFilter"
$filter.EventNamespace = 'root\cimv2'

$result = $filter.Put()
$filterPath = $result.Path

$consumer = ([wmiclass]"\\.\root\subscription:CommandLineEventConsumer").CreateInstance()
$consumer.Name = 'USBConsumer'
$consumer.CommandLineTemplate = "C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe –ExecutionPolicy Bypass -file C:\test.ps1"
$consumer.ExecutablePath = "C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe"
$consumer.WorkingDirectory = "C:\"
$result = $consumer.Put()
$consumerPath = $result.Path

$bind = ([wmiclass]"\\.\root\subscription:__FilterToConsumerBinding").CreateInstance()

$bind.Filter = $filterPath
$bind.Consumer = $consumerPath
$result = $bind.Put()
$bindPath = $result.Path

上面的代码应该在 Windows 检测到插入 USB 设备时运行脚本,它运行良好(没有错误/警告/异常)但是在插入设备时,脚本应该显示一个消息框.没有。我已经自行测试了触发脚本,对话框显示正常。

我真的不是很熟悉 WMI 和持久化的,所以任何帮助都将不胜感激

【问题讨论】:

    标签: powershell usb wmi


    【解决方案1】:

    由于事件使用者将由在 SYSTEM 帐户下运行的 WMI 主机进程调用,因此您不会在自己的桌面会话中看到任何内容。

    如果您将 C:\test.ps1 内容更改为写入事件日志:

    $LogSource = "USB Detector"
    
    if(-not [System.Diagnostics.EventLog]::SourceExists($LogSource))
    {
        New-EventLog -LogName Application -Source $LogSource
    }
    Write-EventLog -LogName Application -Source $LogSource -EventId 100 -Message "New disk attached!"
    

    你会发现它工作正常:

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-03-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-09-28
      相关资源
      最近更新 更多