powershell - 选择字符串的输出在输出中有@{
问题描述
我正在尝试获取处于自动模式但未运行的服务并启动它们,除了我想从脚本中忽略以检查的少数服务之外,是否有办法以正确的格式获得所需的输出,如图所示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)
}
}
解决方案
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
推荐阅读
- javascript - 为什么 TypeScript 在可选链接运算符之后显示“无法调用可能是'未定义'.ts(2722)的对象”错误?
- nginx - 创建 NGINX 服务器代理绕过所有子文件夹和资产
- java - 使用 WSDL 生成的类的单元测试中的 java.lang.ExceptionInInitializerError
- java - RecylerView 不会更新新数据,除非模拟器通过打开和关闭来刷新
- javascript - REACT: Translator Component | Setting & Accessing State
- python - Google Assistant on rgb matrix with Raspberry Pi
- java - 只有在用户选择的情况下,我如何才能使我的扣除有效?
- android - 如何在 APK 文件中找到启动路径?
- javascript - 这是处理 JavaScript 承诺的正确方法吗?
- angular - 测试套件未能运行,Jest 遇到了意外的令牌