stringpowershellget-childitemline-by-line

String line by line


I have to listing files with some string from diferent location , but in the output I required path line by line. All it's OK if in the first locations are files more than one, but if is only one file and in other location are more files than all path are in the one line.

Example:

$files = (Get-ChildItem "C:\temp" | Select-String "test" | group Path).Name

Output:

C:\temp\cca.msi
C:\temp\dfgfg.txt
C:\temp\dghghfgh.txt

Add second location:

$files += (Get-ChildItem "C:\temp2" | Select-String "test" | group Path).Name

Output:

C:\temp\cca.msi
C:\temp\dfgfg.txt
C:\temp\dghghfgh.txt
C:\temp2\file3.txt
C:\temp2\file4.txt

The above is correct.

Below it's wrong from me:

$files = (Get-ChildItem "C:\temp" | Select-String "test" | group Path).Name

Output:

C:\temp\cca.msi

Add more paths:

$files += (Get-ChildItem "C:\temp2" | Select-String "test" | group Path).Name

Output in one line:

C:\temp\cca.msiC:\temp2\file3.txtC:\temp2\file4.txt

What am I doing wrong?


Solution

  • If your first statement produces just a single result the variable $files contains a string, not an array. You can fix that by enforcing an array result, e.g. via the array subexpression operator (@()):

    $files = @((Get-ChildItem "C:\temp" | Select-String "test" | group Path).Name)
    

    or by defining the variable as an array:

    [array]$files = (Get-ChildItem "C:\temp" | Select-String "test" | group Path).Name