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.
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.
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 .
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.
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.
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" $_ })
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With