启动和停止使用WMI和启动作业远程服务
问题描述:
为什么这个工作:启动和停止使用WMI和启动作业远程服务
$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对我有用。通过使用开始作业,我想在接下来的服务之前使用
$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变量未在后台作业的范围内定义。
所以,如果我正确地理解这一点,$ bits变量为空,因为它没有在开始工作scriptblock中定义? –
是的。 $位未在本地作用域中定义。 –