Search code examples
powershellhigher-order-functionsarray-map

Select/map each item of a Powershell array to a new array


I have an array of file names in Powershell, and I would like to prepend a path to each of them and get the result in a new array.

In C# I could do this using Linq...

var files = new string[] { "file1.txt", "file2.txt" };
var path = @"c:\temp\";
var filesWithPath = files.Select(f => path + f).ToArray();

But what is the idiomatic way to do this in Powershell? It looks like there is a foreach syntax I could use, but I figure there must be a more concise, functional way to do it.


Solution

  • An array in Powershell is declared with @() syntax. % is shorthand for foreach-object. Let's declare an array with all the file names and loop through it with foreach. join-path combines a path and a child path into a single path.

    $files = @("file1.txt", "file2.txt")
    $pFiles = $files | % {join-path "c:\temp" $_ }
    $pFiles
    

    Output:

    c:\temp\file1.txt
    c:\temp\file2.txt
    

    NB: if the input consists of single an element, foreach will not return a collection. If an array is desired, either use explicit type or wrap the results. Like so,

    [array]$pFiles = $files | % {join-path "c:\temp" $_ }
    $pFiles = @($files | % {join-path "c:\temp" $_ })