Reputation: 162
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!
Upvotes: 1
Views: 1565
Reputation: 405
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()
}
Upvotes: 0
Reputation: 1790
In PowerShell 7.x, WMI isn't supported any more. In that case you'd need to use CIM instead. Besides, using CIM has a bunch of advantages (and some disadvantages).
$Creds = Get-Credential
$Bits = Get-CimInstance `
-Class Win32_Service `
-ComputerName 'computer' `
-Credential $Creds `
-Filter 'Name LIKE "bits%"'
Start-Job {
$Using:Bits | Invoke-CimMethod -MethodName StopService
} | Receive-Job -Wait
Ref 1: MS DevBlogs - Should I use CIM or WMI with Windows PowerShell?
Ref 2: MS Learn - Getting WMI objects with Get-CimInstance
Upvotes: 0
Reputation: 18176
The $bits variable isn't defined in the scope of the background job.
Upvotes: 0