简体   繁体   中英

Start all automatic services not running

I'm trying to further automate our Windows patching to automatically attempt to start any services that are set to Auto but are not running.

Below is what I've tried so far with no success:

$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
}

Here is the error I'm getting:

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

Is there something I'm missing?

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

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

I ended up using Adrian R's suggestion and it works great. Here's the final version:

#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"

FYI if you don't exclude the SPPSVC you'll get the below error: Set-Service : Service 'Software Protection (sppsvc)' cannot be configured due to the following error: Access is denied

Thanks everyone!

The -ExpandProperty option will work. You can also use the following example:

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

Piping the results into foreach will provide you with a stream of values.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM