Search code examples
powershellwmi

Starting and stopping a remote service using WMI and Start-Job


Why does this work:

$bits = Get-WmiObject -Class win32_service -ComputerName computer -Credential $creds | 
? name -Like "bits*"

$bits.StopService()

but with this

$bits = Get-WmiObject -Class win32_service -ComputerName computer -Credential $creds | 
? name -Like "bits*"

$stopbits = Start-Job {$bits.StopService()}

I get an error "You cannot call a method on a null-valued expression"

I'm trying to write a script that will stop a set of services in a set order. I only have WMI available to me. By using Start-Job I want to then use

$stopbits = Start-Job {$bits.StopService()}
Wait-Job -Id $stopbits.id 

before going to the next service. I am a powershell beginner so I could be going about this all wrong. I would appreciate any help on getting this to work. Thank you!


Solution

  • You need to invoke WMI Method called StopService to execute the job. Something like this.

    $stopbits = Start-Job {
      $bits.InvokeMethod("StopService",$null)
    }
    

    On second thoughts, the above code won't work too as $bits object is not defined in the local scope. So you need to do this.

    $global:creds = Get-credential
    $stopbits = Start-Job {
      $bits = Get-WmiObject `
        -Class win32_service `
        -ComputerName $computer `
        -Credential $global:creds | 
          where name -Like "bits*"
      $bits.StopService()
    }