Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 869
Jon Rimmer Avatar asked Jan 18 '12 10:01

Jon Rimmer


People also ask

How do I separate values from an array in PowerShell?

Split() function splits the input string into the multiple substrings based on the delimiters, and it returns the array, and the array contains each element of the input string. By default, the function splits the string based on the whitespace characters like space, tabs, and line-breaks.

Does map return a new array?

The map() method returns an entirely new array with transformed elements and the same amount of data. In the case of forEach() , even if it returns undefined , it will mutate the original array with the callback .

How do you access array elements in PowerShell?

To access items in a multidimensional array, separate the indexes using a comma ( , ) within a single set of brackets ( [] ). The output shows that $c is a 1-dimensional array containing the items from $a and $b in row-major order.

How do you create a new array on a map?

The map() method in JavaScript creates an array by calling a specific function on each element present in the parent array. It is a non-mutating method. Generally map() method is used to iterate over an array and calling function on every element of array.


1 Answers

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" $_ }) 
like image 103
vonPryz Avatar answered Sep 19 '22 05:09

vonPryz