我有以下功能,我註冊停止服務事件。 服務停止後,我想在該事件中顯示該ServiceName。但是,不知何故,下面的代碼不想打印服務名稱?Register-WmiEvent(Win32_ProcessStopTrace) - 如何在-Action開關中使用變量?
請參閱Write-Host $ControllerSvc,」 stopped 」
在 - 行動開關它打印只是「停止」。但是,如果我的代碼更改爲這是罰款 -
Write-Host $e.ProcessName,」 stopped 」
(我不希望因爲我的過程或imagename是同樣爲所有的服務它像SVCHOST)
function Stop-MyService($SystemName)
{
$ControllerSvc = $SystemName+"Controller"
$svc = gwmi win32_service -filter "name = `"$ControllerSvc`""
$ControllerPid = $svc.ProcessId
Register-WMIEvent -query 「SELECT * FROM Win32_ProcessStopTrace WHERE ProcessID=$ControllerPid」 -SourceIdentifier 「ControllerSvcEvent」 -action {
$e = $Event.SourceEventArgs.NewEvent
Write-Host $ControllerSvc,」 stopped 」 #**** never prints out the variable****
unregister-event -sourceIdentifier 「ControllerSvcEvent」
}
Stop-Service $ControllerSvc
}
NB:爲了簡單起見,我在這裏展示了一種服務。其實 有多種服務,其中停止其中一個停止 其他人。所以,我想顯示在事件中停止的服務名稱 。
不起作用。我試過這個 - 「註冊WMIEvent -query」選擇*從Win32_ProcessStopTrace WHERE ProcessID = $ ControllerPid「-SourceIdentifier」ControllerSvcEvent「-MessageData $ ControllerSvc -action { $ e = $ Event.SourceEventArgs.NewEvent 寫主機$ ControllerSvc, 「停止」 unregister-event -sourceIdentifier「ControllerSvcEvent」 } ' –
是的,但是您需要將'Write-Host $ ControllerSvc'更改爲'Write-Host $ Event.MessageData'。 – Neolisk