我试图获取处于自动模式但未运行并启动它们的服务,但我想从脚本中忽略的少数服务除外,是否有办法以正确的格式获取所需的输出,如下所示:如图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)
}
}
答案 0 :(得分:0)
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