简体   繁体   English

使用Register-WmiEvent通知脚本何时开始执行

[英]Using Register-WmiEvent to notify when a script starts executing

I'm totally new to PS and I've been trying to come up with a way to detected when a script, say Foo.(ps1 | pl | py | bar) begins execution so that I may run a powershell script upon that event. 我是PS的新手,我一直想着想出一种方法来检测脚本(例如Foo)何时开始执行。 。 I've started with using the following example from MSDN and I've added an if statement to filter everything except PS executions. 我从使用MSDN的以下示例开始,并添加了if语句来过滤除PS执行之外的所有内容。

$Query = 'SELECT * FROM Win32_ProcessStartTrace'            
$action = {            
    $e = $Event.SourceEventArgs.NewEvent 
    if($e.ProcessName -eq "powershell.exe") {           
        $fmt = 'ProcessStarted: (ID={0,5}, Parent={1,5}, Time={2,20}, Name="{3}")'            
        $msg = $fmt -f $e.ProcessId, $e.ParentProcessId, $event.TimeGenerated, $e.ProcessName            
        Write-host -ForegroundColor Red $msg            
    }
}            
Register-WmiEvent -Query $Query -SourceIdentifier ProcessStart -Action $Action  

The code now detects when powershell instance is started, but I haven't found a way to access and filter the arguments passed to the instance. 该代码现在可以检测到何时启动powershell实例,但是我还没有找到一种方法来访问和过滤传递给该实例的参数。 I would like to ensure that I only take action for the Foo script not any other PS script. 我想确保只对Foo脚本采取措施,而不对其他PS脚本采取措施。 Is there a way to access the arguments for the started powershell process? 是否可以访问已启动的Powershell进程的参数?

Give this a try, you can try to match your script against the CommandLine property of the new process: 尝试一下,您可以尝试将脚本与新进程的CommandLine属性进行匹配:

Register-WmiEvent -Query "SELECT * FROM __InstanceCreationEvent WITHIN 2 WHERE TargetInstance isa 'Win32_Process'" -SourceIdentifier NewPSProcess -Action {
    $e = $EventArgs.NewEvent.TargetInstance
    if($e.Name -eq 'powershell.exe')
    {
        #if($e.CommandLine -match 'yourScript') { ... }
        Write-host $e.CommandLine
    }
}

sleep 5
powershell -file c:\test.ps1

UPDATE 更新
Here's an update code that captures only powershell.exe process creation (on the query level) and writes the commandLine value to a text file. 这是一个更新代码,仅捕获powershell.exe进程创建(在查询级别),并将commandLine值写入文本文件。 I was able to view all powershell process creations (made from cmd) written to the file. 我能够查看所有写入文件的Powershell流程创建内容(由cmd创建)。

$query = 'Select * From __InstanceCreationEvent Within 2 Where TargetInstance Isa "Win32_Process" And TargetInstance.Name = "powershell.exe"'
Register-WMIEvent -Query $query -SourceIdentifier NewPSProcess -Action {
   $EventArgs.NewEvent.TargetInstance.CommandLine | Out-File D:\scripts\temp\psevent.txt -Append
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM