Search code examples
windowspowershellfilenamesstring-concatenationprepend

Prepend folder name to paths in an array


I'm looking to prepend a folder name to the start of an array of (relative) paths using a foreach statement, but it's not making any changes to the array (no errors either)

Note: This is more for educational purposes than functional as I have it working using a for loop which I've commented out, but I'm interested in learning how the foreach statement works

$myFiles = @(
    "blah1\blah2\file1.txt"
    "blah3\blah4\file2.txt"
    "blah5\blah6\file3.txt"
)

$checkoutFolder = "folder1"

#for ($h = 0; $h -lt $myFiles.Length; $h++) {
#$myFiles[$h] = $checkoutFolder + "\" + $myFiles[$h]
#}

foreach ($path in $myFiles) {
$path = $checkoutFolder + "\" + $path
}

$myFiles

I also tried using a buffer variable e.g.

$buffer = $checkoutFolder + "\" + $path
$path = $buffer

But same result i.e. OUTPUT:

blah1\blah2\file1.txt
blah3\blah4\file2.txt
blah5\blah6\file3.txt

Solution

  • I could think of two ways:

    Create new array with modified data of old array

    $myFiles = @(
                "blah1\blah2\file1.txt"
                "blah3\blah4\file2.txt"
                "blah5\blah6\file3.txt"
                )
    $checkoutFolder = "folder1"
    
    #Create new array $myFilesnew
    $myFilesnew = @()
    #For each line in in old array
    foreach ($file in $myFiles)
    {
    #Create new row from modied row $file of $myFiles array
    $row = $checkoutFolder+"\"+$file
    #Add row $row to a new array $myFilesnew
    $myFilesnew+=$row
    }
    
    $myFilesnew
    

    Modify each row of existing array:

    $myFiles = @(
                "blah1\blah2\file1.txt"
                "blah3\blah4\file2.txt"
                "blah5\blah6\file3.txt"
                )
    $checkoutFolder = "folder1"
    
    $i=0
    while($i-lt $myFiles.Count)
        {
         #Get $i row $myFiles[$i] from aray, perform insert of modified data, write data back to $myFiles[$i] row of the array
         $myfiles[$i]=$myFiles[$i].Insert(0,$checkoutFolder+"\");
         #Add +1 to $i
         $i++
    
            }
    $myFiles