首页 > 解决方案 > 选择字符串的输出在输出中有@{

问题描述

我正在尝试获取处于自动模式但未运行的服务并启动它们,除了我想从脚本中忽略以检查的少数服务之外,是否有办法以正确的格式获得所需的输出,如图所示2,由于选择字符串输出我的脚本如果不能将 service.name 作为变量。我正在使用以下命令

Get-CimInstance win32_service -Filter "startmode = 'auto' AND state != 'running' "  | select name, startname, exitcode | Select-String   "gupdate|RemoteRegistry"  -NotMatch

我得到的输出是

但所需的输出是

下面是我的脚本

    $Services = Get-CimInstance win32_service -Filter "startmode = 'auto' AND state != 'running' "  | select name, startname, exitcode | Select-String  -Pattern "gupdate|RemoteRegistry" -NotMatch
$ServicesRunning = Get-CimInstance win32_service -Filter "state = 'running'"
if ([string]::IsNullOrEmpty($Services)){
    Write-Output "OK: All services running | ServicesRunning=$($ServicesRunning.Count);0;0;0;0"
    $host.SetShouldExit(0)
}
else{
    $ServicesStopped=""
    ForEach ($Service in $Services){
        Start-Service @($Service.Name) -ErrorAction SilentlyContinue | Out-Null  
        if ($(Get-Service -Name ($Service.Name)).Status -eq "running"){
            $ServicesStopped += "($Service.Name)(Started manually),"
            If ($ExitCode -eq 0){
                $ExitCode = 1
            }
        }
        Else{
            $ServicesStopped += "$($Service.Name)(Stopped),"
            $ExitCode = 2
        }
    }
    If ($ExitCode -eq 2){
        Write-Output "CRITICAL: Service(s) stopped: $($ServicesStopped.TrimEnd(",")) | ServicesRunning=$($ServicesRunning.Count);0;0;0;0"
        $host.SetShouldExit(2)
    }
    Else{
        Write-Output "WARNING: Service(s) stopped: $($ServicesStopped.TrimEnd(",")) | ServicesRunning=$($ServicesRunning.Count);0;0;0;0"
        $host.SetShouldExit(1)
    }
}

标签: powershell

解决方案


Select-String需要一个字符串或字符串列表作为输入。Select-Object生成自定义对象列表。将后者插入前者会导致后者的输出转换为字符串。这显然不是你想要的。无论如何都不需要它,因为您可以直接通过Get-CimInstance参数进行所有过滤-Filter

$fltr = "name!='gupdate' AND name!='RemoteRegistry'" + 
        " AND startmode='auto' AND state!='running'"

Get-CimInstance Win32_Service -Filter $fltr |
    Select-Object Name, StartName, ExitCode

推荐阅读