不启动所有自动服务 运行

Start all automatic services not running

我正在尝试进一步自动化我们的 Windows 修补程序,以自动尝试启动任何设置为自动但不是 运行 的服务。

以下是我迄今为止尝试过但没有成功的方法:

$stoppedServices = Get-WmiObject win32_service -ComputerName $computer -Filter "startmode = 'auto' AND state != 'running'" | select name

foreach ($stoppedService in $stoppedServices) {
  Set-Service -Service $stoppedService -Status Running
}

这是我遇到的错误:

Set-Service : Service @{name=RemoteRegistry} was not found on computer '.'.
At line:4 char:13
+             Set-Service -Service $stoppedService -Status Running
+             ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo          : ObjectNotFound: (.:String) [Set-Service], InvalidOperationException
+ FullyQualifiedErrorId : InvalidOperationException,Microsoft.PowerShell.Commands.SetServiceCommand

有什么我遗漏的吗?

您需要使用参数 -Expand,否则您仍然有一个带有 属性 Name 的对象,而不是 属性:[=13 的值=]

$stoppedServices = Get-WmiObject win32_service ... | select <b>-Expand</b> name

-ExpandProperty 选项将起作用。您还可以使用以下示例:

$stoppedServices = Get-WmiObject win32_service -ComputerName $computer -Filter "startmode = 'auto' AND state != 'running'" | foreach {$_.Name}

将结果通过管道传输到 foreach 将为您提供一个值流。

参考: http://blogs.msdn.com/b/powershell/archive/2009/09/14/select-expandproperty-propertyname.aspx

我最终采用了 Adrian R 的建议并且效果很好。这是最终版本:

#Start all non-running Auto services Get-WmiObject win32_service -ComputerName $computer -Filter "startmode = 'auto' AND state != 'running' AND name != 'sppsvc'" | Invoke-WmiMethod -Name StartService #Output any services still not running $stoppedServices = Get-WmiObject win32_service -ComputerName $computer -Filter "startmode = 'auto' AND state != 'running' AND name != 'sppsvc'" | select -expand Name Write-Host "$env:ComputerName : Stopped Services: $stoppedServices"

仅供参考,如果您不排除 SPPSVC,您将收到以下错误: Set-Service : Service 'Software Protection (sppsvc)' cannot be configured due to the following error: Access is denied

谢谢大家!