繁体   English   中英

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

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

我想创建一个 PS 脚本,它将显示所有已停止的自动服务,然后尝试启动这些服务。

下面是PS代码。 它成功地显示了远程服务器上所有停止的服务。

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

您可以简单地将查询结果存储到一个变量中,而不是选择和显示它,并且您将拥有一堆win32_Service实例,它们都有一个StartService()方法。 检查您正在使用的 wmi 类的文档通常是个好主意,它们中的大多数都有对所表示的对象起作用的方法,而不必像大多数 Powershell 对象一样将它们通过管道传递到其他 cmdlet:

Win32_Service 类方法

你会像这样使用它:

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

除非您需要使用 WMI,否则还可以考虑使用 Get-Service。 您有一些不同之处,但想法是相同的:

    $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

此外,您还可以使用-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