Search code examples
windowspowershellget-childitem

Print cusrom strings between output lines of Get-Child items in Powershell


need your little help here. I am trying to print custom string in between output of Get-ChildItem cmdlet in Powershell but I am not sure how to get that done.

For example, I am trying to find all files which has keyword "PostTestScript" in them and I am doing below.

Get-ChildItem | Select-String -Pattern "PostTestScript"

And this is the output its generating

aaa1.txt:31:    PostTestScript     = ''
aaa2.txt:31:    PostTestScript     = ''
aaa3.txt:31:    PostTestScript     = '' 

Now what should I do if I want to print custom output(doted line) in between filenames like below ?

aaa1.txt:31:    PostTestScript     = ''
-------------------------------------------
aaa2.txt:31:    PostTestScript     = ''
-------------------------------------------
aaa3.txt:31:    PostTestScript     = '' 
-------------------------------------------

Solution

  • Line separator after each output line

    $pattern = "PostTestScript"
    Get-ChildItem | Select-String -Pattern $pattern | 
        ForEach-Object {
            $_
            '-'*50       
        }
    

    Line separator on filename change

    $pattern = "PostTestScript"
    $lastFile = [string]::Empty
    Get-ChildItem | Select-String -Pattern $pattern | 
        ForEach-Object {
            if (($lastFile -ne [string]::Empty) -and ($_.FileName -ne $lastFile)) {
                '-'*50       
            }
            $lastFile = $_.FileName
            $_
        }
    '='*50                   ### line separator at utter end (optional)
    

    Line separator after each $everyN output lines

    $pattern = "PostTestScript"
    $everyN = 4
    $i = 0
    Get-ChildItem | Select-String -Pattern $pattern | 
        ForEach-Object {
            if (($i -ne 0) -and ($i % $everyN) -eq 0) {
                '-'*50
            }
            $i++
            $lastFile = $_.FileName
            $_
        }
    '='*50                   ### line separator at utter end (optional)