简体   繁体   English

Powershell 显示所有已停止的自动服务并尝试启动这些服务

[英]Powershell to display all automatic services that are stopped and attempt to start those services

I want to create a PS script where it will display all the automatic services that are stopped, and will attempt to start the services afterward.我想创建一个 PS 脚本,它将显示所有已停止的自动服务,然后尝试启动这些服务。

Below is the PS code.下面是PS代码。 It is successfully displayed all the stopped services on remote server.它成功地显示了远程服务器上所有停止的服务。

Get-WmiObject Win32_Service -ComputerName SERVER1, SERVER2 |`
where     {($_.startmode -like "*auto*") -and `
        ($_.state -notlike "*running*") -and `
        ($_.name -notlike "gupdate") -and `
        ($_.name -notlike "remoteregistry") -and `
        ($_.name -notlike "sppsvc") -and `
        ($_.name -notlike "lltdsvc") -and `
        ($_.name -notlike "KDService") -and `
        ($_.name -notlike "wuauserv")
        }|`

        select DisplayName,Name,StartMode,State,PSComputerName|ft -AutoSize

You can simply store the results of your query into a variable instead of selecting and displaying it, and you'd have a bunch of win32_Service instances that all have a StartService() method.您可以简单地将查询结果存储到一个变量中,而不是选择和显示它,并且您将拥有一堆win32_Service实例,它们都有一个StartService()方法。 It's generally a good idea to check the docs of the wmi classes you're using, most of them have methods that act on the object being represented, instead of having to pipe them around to other cmdlets like most Powershell objects:检查您正在使用的 wmi 类的文档通常是个好主意,它们中的大多数都有对所表示的对象起作用的方法,而不必像大多数 Powershell 对象一样将它们通过管道传递到其他 cmdlet:

Win32_Service class methods Win32_Service 类方法

You'd use it like this:你会像这样使用它:

    $services = Get-WmiObject Win32_Service -ComputerName SERVER1, SERVER2 |`
    where     {($_.startmode -like "*auto*") -and `
    # [...]
    }

    $service | select DisplayName,Name,StartMode,State,PSComputerName|ft -AutoSize
    $Service | ForEach {$_.StartService()}

Consider also using Get-Service unless you have a requirement for using WMI.除非您需要使用 WMI,否则还可以考虑使用 Get-Service。 You have a couple differences but the idea is the same:您有一些不同之处,但想法是相同的:

    $Services = Get-Service -ComputerName SERVER1,SERVER2 |`
    where     {($_.StartType -eq "Automatic") -and `
    ($_.Status -notlike "*running*") -and `
    ($_.Name -notlike "gupdate") -and `
    # ...
    }
    $Services | select Description,Name,StartType,Status,MachineName |ft -AutoSize
    $Services | Start-Service

Also, you could also simplify your filter a lot by using the -notin operator:此外,您还可以使用-notin运算符来大大简化过滤器:

    where     {($_.startmode -like "*auto*") -and `
    ($_.state -notlike "*running*") -and `
    ($_.name -notin "gupdate","remoteregistry","sppsvc","lltdsvc","KDService","wuauserv")
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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