Person
Person

Reputation: 1

running a powershell script from command prompt?

The following script (which will stop IIS service when AppMgmt service is stopped) runs successfully in "PowerGUI Script Editor", but when running it from console "powershell -file path_to_script" it does not execute action when the event is fired:

function Watch-MyService()
{
   $query = "SELECT * FROM __InstanceModificationEvent WITHIN 2 " +
             "WHERE TargetInstance Isa 'Win32_Service' " +
             "AND TargetINstance.Name = 'AppMgmt'" +
             "AND TargetInstance.State = 'Stopped'"

    $action = 
    { 
        Write-Host "stopping service # 2" 
        Stop-Service 'W3SVC' -Force
    }
    Write-Host "registering event"  
    Register-WMIEvent -query $query -SourceIdentifier "ControllerSvcEvent" -action $action
}

Watch-MyService

in console, I only see:

Registering event

but nothing else displays when stopping the 'AppMgmt' service, no output to the console, & the IIS service stays unaffected.

the console is started with admin privileges.

Upvotes: 0

Views: 903

Answers (1)

Keith
Keith

Reputation: 21

When you run your PowerShell script from the command prompt in this way, your script executes and then the PowerShell process likely exits (open task manager to watch the PowerShell process stop as soon as your script does). The listener for your event (PowerShell) is no longer running, since the process has exited. The event registration scope is limited to the scope of the PowerShell session.

Upvotes: 2

Related Questions