2

I want to use select-string on the output of another command (similar to how one would use grep on a Unix OS).

Here is the output of the command without the select-string:

> (dir resources).Name
wmd-Linux-22022.json
wmd-Linux-22023.json
wmd-Linux-22024.json
wmd-Windows-22022.json
wmd-Windows-22023.json
wmd-Windows-22024.json

When I use select-string, I get blank lines for some reason:

> (dir resources).Name | select-string Windows

wmd-Windows-22022.json
wmd-Windows-22023.json
wmd-Windows-22024.json


How can I either (A) tell select-string to eat the blank lines with no matches, or (B) pipe the output to another powershell utility that could eat the blank lines for me?

1
  • 2
    an alternative would be (dir resources\*windows*).name
    – Balthazar
    Commented May 31, 2022 at 17:28

3 Answers 3

2

Select-String returns an array of MatchInfo, as shown by ((dir resources).Name | select-string Windows)[0].GetType()

To get what you're after, just cast your entire expression to [string[]]:

[string[]]((dir resources).Name | select-string Windows)

2

I found one solution:

((dir resources).Name | select-string Windows | out-string).Trim()

out-string converts an input from another command to a string, and Trim() is a function that only works on strings (i.e., Trim() won't work on the output of a command that returns some non-string type).

0

Here is an all-in-one function to easily write list (as output result), blank lines are removed, it can be piped. 2 examples of use shown below Hope this help

function Write-List {
    Param(
        [Parameter(Mandatory, ValueFromPipeline)][array] $Array,
        [string]$Prefixe,
        [bool]$Numbering = $False
    )
    if ($Numbering) { 
        $NumberOfDigit = $($Array.Count).ToString().Length

        $Array | Format-List | Out-String -Stream | ForEach-Object -Process {
            if (-not [string]::IsNullOrWhiteSpace($_)) {
                "$Prefixe# {0,$NumberOfDigit} : {1}" -f (++$Index), $_
            }
        }
    } else {
        $Array | Format-List | Out-String -Stream | ForEach-Object -Process {
            if (-not [string]::IsNullOrWhiteSpace($_)) {
                "$Prefixe{0}" -f $_
            }
        }
    }
}

Example #1 :

Write-List @("titi", "toto", "tata", "titi", "toto", "tata", "titi", "toto", "tata", "titi", "toto", "tata") -Numbering $True
#  1 : titi
#  2 : toto
#  3 : tata
#  4 : titi
#  5 : toto
#  6 : tata
#  7 : titi
#  8 : toto
#  9 : tata
# 10 : titi
# 11 : toto
# 12 : tata

Example #2 :

Get-Service -Name "*openvpn*" | Select-Object DisplayName,Name,Status,StartType | Write-List -Prefixe " - "
 - DisplayName : OpenVPN Interactive Service
 - Name        : OpenVPNServiceInteractive
 - Status      : Running
 - StartType   : Automatic

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .