I have the following function where I register for the stop service event.
Once the service is stopped, I want to display that ServiceName in the event. But, somehow, the code below does not wants to print service name ?
See the Write-Host $ControllerSvc,” stopped ” in the -Action switch It prints justs ” stopped”. But, if I change the code to this it is fine –
Write-Host $e.ProcessName,” stopped ” (which I do not want because my process or imagename is same for all the services. Its something like 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:For sake of simplicity I am showing one service here. Actually
there are multiple services where stopping one of them stops the
others. So, I want to display the service names which are getting
stopped in the event.
Try passing
$ControllerSvcthrough-MessageDataparameter ofRegister-WMIEvent, then it should be accessible through$Event, according to this article.