Search code examples
powershellstring-formatting

PowerShell concatenate output of Get-ChildItem


I have a working script that searches for files with a regular expression. The script returns 2 lines per file: the parent folder naùe, and the filename (matching the regex).

Get-ChildItem -Path "D:\test\" -Recurse -File |
  Where-Object { $_.BaseName -match '^[0-9]+$' } |
    ForEach-Object { $_.FullName -Split '\',-3,'SimpleMatch' } | 
     select -last 2 | 
       Out-File "D:\wim.txt"

A certain system needs to have the output on one line, concatenated with for example \ or a similar character. How can I achieve this please ?

Many thanks !


Solution

  • Get-ChildItem -Path D:\test -Recurse -File | 
      Where-Object { $_.BaseName -match '^[0-9]+$' } | 
        ForEach-Object { ($_.FullName -split '\\')[-2,-1] -join '\' } |                          #'
          Out-File D:\wim.txt
    
    • ($_.FullName -Split '\\')[-2,-1] extracts the last 2 components from the file path
    • and -join '\' joins them back together.

    Note that, aside from the line-formatting issue, your original command does not work as intended, because | select -last 2 is applied to the overall output, not per matching file; thus, even if there are multiple matching files, you'll only ever get the parent directory and filename of the last matching file.

    The command above therefore extracts the last 2 \-separated path components inside the ForEach-Object block, directly on the result of the -split operation, so that 2 (joined) components are returned per file.

    As an aside, the -3 in $_.FullName -split '\', -3, 'SimpleMatch' does not extract the last 3 tokens; it is currently effectively treated the same as 0, meaning that all resulting tokens are returned; given that -split defaults to using regexes, and representing a literal \ requires escaping as \\, $_.FullName -split '\', -3, 'SimpleMatch' is the same as $_.FullName -split '\\', which is what the solution above uses.

    Note that there is a green-lit -split enhancement that will give negative <Max-substrings> values new meaning in the future, applying the current positive-number logic analogously to the end of the input string; e.g, -3 would mean: return the last 2 components plus whatever is left of the input string before them (with the resulting tokens still reported from left to right).