Trying to setup a powershell monitor for maintenance mode value from the output of ./repcli status:
This returns a long list of values and I'm trying to return the status for maintenance mode being [disabled] or [enabled]
The line of interest looks like this, for example:
Maintenance mode = [enabled]
I'd like to determine whether the line of interest contains [enabled] or [disabled], and return 1 in the former case, 0 in the latter.
What I tried:
./repcli.exe status | out-string | select-string -pattern 'maintenance'
This returns all output lines, which is not what I want.
CodePudding user response:
Try the following:
# In the output from ./repcli.exe status, extract the line that contains
# substring 'maintenance' and see if it contains substring '[enabled]'
# Note: In PSv7 , you can replace '| ForEach Line' with '-Raw'
$enabled =
(./repcli.exe status | Select-String maintenance | ForEach Line) -match '\[enabled\]'
# Map the enabled status to 1 ($true) or 0 ($false)
return [int] $enabled
Note the use of the -match operator, which, due to being regex-based, requires escaping [ and ] with \ in order to be used literally. Select-String too uses regexes, except if you pass -SimpleMatch.
As for what you tried:
Out-String(without-Stream) returns a single string, comprising all the lines output by your./repcli.execall.Therefore, if
Select-Stringfinds a match, it returns the entire string, not just the line on which the pattern is found.You can avoid that problem by simply omitting the
Out-Stringcall, given that PowerShell automatically relays output lines from calls to external programs line by line.While
Select-Stringthen only returns matching lines, note that it doesn't do so directly, but wraps them in Microsoft.PowerShell.Commands.MatchInfo instances that accompany the actual line text, in property.Line, with metadata about the match.- Pipe to
| ForEach Lineor, in PowerShell (Core) 7 only, add the-Rawswitch to get only the line text.
- Pipe to
Of course, you then need to examine the line text returned for the substring of interest, as shown above.
