为什么这有效:
$bits = Get-WmiObject -Class win32_service -ComputerName computer -Credential $creds |
? name -Like "bits*"
$bits.StopService()
但是有了这个
$bits = Get-WmiObject -Class win32_service -ComputerName computer -Credential $creds |
? name -Like "bits*"
$stopbits = Start-Job {$bits.StopService()}
我收到错误“您无法在空值表达式上调用方法”
我正在尝试编写一个脚本来按设定的顺序停止一组服务。我只有 WMI 可用。通过使用 Start-Job 我想使用
$stopbits = Start-Job {$bits.StopService()}
Wait-Job -Id $stopbits.id
在进行下一次服务之前。我是一个 powershell 初学者,所以我可能会搞错。我将不胜感激任何帮助使其发挥作用的帮助。谢谢!
您需要调用名为 StopService 的 WMI 方法来执行作业。 像这样的东西。
$stopbits = Start-Job {$bits.InvokeMethod("StopService",$null)}
再考虑一下,上面的代码也不起作用,因为 $bits 对象没有在本地范围中定义。 所以你需要这样做。
$global:creds = Get-credential
$stopbits = Start-Job {
$bits = Get-WmiObject -Class win32_service -ComputerName $computer -Credential $global:creds | ? name -Like "bits*"
$bits.StopService()
}
$bits 变量未在后台作业的范围内定义。
在 PowerShell 7.x 中,不再支持 WMI。在这种情况下,您需要使用 CIM。 此外,使用 CIM 有很多优点(也有一些缺点)。
$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
参考 1:MS DevBlogs - 我应该将 CIM 或 WMI 与 Windows PowerShell 一起使用吗?
参考资料 2:MS Learn - 使用 Get-CimInstance 获取 WMI 对象