Question

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!

Was it helpful?

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 | ? name -Like "bits*"
$bits.StopService()
}

OTHER TIPS

The $bits variable isn't defined in the scope of the background job.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top