我想你要尋找的可能是WMI事件觸發。你可以註冊(並響應)內WMI發生的事件,諸如:
- 當過程開始或停止
- 當一個服務啓動或停止
- 當一個進程超過一定量的存儲器使用
- 當安裝一個新版本的設備驅動程序
- 當計算機被分配給一個新的組織單位
- 當接通或斷開一個用戶登錄
- 當環境變量改變
- 當筆記本電腦的電池下降到低於某個閾值
- 千其他情況下
要WMI事件註冊,使用Register-WmiEvent
小命令。您可以使用-Action
參數來聲明在檢測到匹配事件時要執行的PowerShell語句。下面是一個簡單的例子:
# 1. Start notepad.exe
notepad;
# 2. Register for events when Notepad disappears
# 2a. Declare the WMI event query
$WmiEventQuery = "select * from __InstanceDeletionEvent within 5 where TargetInstance ISA 'Win32_Process' and TargetInstance.Name = 'notepad.exe'";
# 2b. Declare the PowerShell ScriptBlock that will execute when event is matched
$Action = { Write-Host -ForegroundColor Green -Object ('Process stopped! {0}' -f $event.SourceEventArgs.NewEvent.TargetInstance.Name) };
# 2c. Register for WMI events
Register-WmiEvent -Namespace root\cimv2 -Query $WmiEventQuery -Action $Action -SourceIdentifier NotepadStopped;
# 3. Stop notepad.exe
# Note: For some reason, if you terminate the process as part of the same thread, the event
# doesn't seem to fire correctly. So, wrap the Stop-Process command in Start-Job.
Start-Job -ScriptBlock { Stop-Process -Name notepad; };
# 4. Wait for event consumer (action) to fire and clean up the event registration
Start-Sleep -Seconds 6;
Unregister-Event -SourceIdentifier NotepadStopped;
FYI:我開發了一個名爲PowerEvents PowerShell的模塊,在CodePlex上託管。該模塊包含註冊永久性WMI事件訂閱的功能,並且包含30多頁PDF文檔,可幫助您瞭解WMI事件。你可以在http://powerevents.codeplex.com找到這個開源項目。
如果我想讓你的代碼適應一些對你來說更實用的代碼,它可能看起來像下面的例子。您可以使用Windows任務計劃程序定期調用代碼。
# 1. If process is not running, then exit immediately
if (-not (Get-Process -Name notepad)) { throw 'Process is not running!'; return; }
# 2. Register for events when Notepad disappears
# 2a. Declare the WMI event query
$WmiEventQuery = "select * from __InstanceDeletionEvent within 5 where TargetInstance ISA 'Win32_Process' and TargetInstance.Name = 'notepad.exe'";
# 2b. Declare the PowerShell ScriptBlock that will execute when event is matched
# In this case, it simply appends the value of the $event automatic variable to a
# new, global variable named NotepadEvent.
$Action = { $global:NotepadEvent += $event; };
# 2c. Register for WMI events
Register-WmiEvent -Namespace root\cimv2 -Query $WmiEventQuery -Action $Action -SourceIdentifier NotepadStopped;
# 3. Wait indefinitely, or until $global:NotepadEvent variable is NOT $null
while ($true -and -not $global:NotepadEvent) {
Start-Sleep -Seconds 600;
(Invoke-WebRequest -Method post 'Http://website.com').Content;
}
您可能會考慮使用進程審計在應用程序啓動時生成日誌事件,並在Task Scheduler看到日誌中的啓動事件時運行該腳本。 – mjolinor