启动所有未运行的自动服务

时间:2015-08-21 19:49:39

标签: powershell powershell-remoting

我正在尝试进一步自动化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

我有什么遗失的吗?

3 个答案:

答案 0 :(得分:1)

您需要使用参数-Expand,否则您仍然拥有一个具有属性Name的对象,而不是该属性的值:

$stoppedServices = Get-WmiObject win32_service ... | select -Expand name

答案 1 :(得分:1)

我最终使用了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

谢谢大家!

答案 2 :(得分:0)

-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