Cataster
Cataster

Reputation: 3481

How to append a path to every file to be stored in array?

suppose i have an array

$f_attachments = @()

every file i have, i simply append to it

$f_attachments += $file

however, i would like to include the directory as well for every file saved in this array

in other words, instead of having to do something like this:

$f_attachments += $currentFolder\$file1
$f_attachments += $currentFolder\$file2
etc...

can i just append it at the array level?

$f_attachments = @($currentFolder)

more explanation

i have a HUGE script. i am appending files (i.e. $f_attachments += $file1 $f_attachments += $file2, etc...) to $f_attachments array at random parts of the script. this array is defined at the VERY BEGINNING

$f_attachments = @()

suppose my full script is like this:

$f_attachments = @()
if() 
{
do something...
$f_attachments += $currentFolder\$file1
}
else
{
do something...
$f_attachments += $currentFolder\$file2
}
....

as you can see, i added $currentFolder\ everytime i am adding a file to the array

i want something at the array definition level, here $f_attachments = @()

that will automatically append this $currentFolder\

in other words, an ideal solution would look like this:

$f_attachments = @($currentFolder\)
if() 
{
do something...
$f_attachments += $file1
}
else
{
do something...
$f_attachments += $file2
}
....

Upvotes: 0

Views: 338

Answers (1)

ArcSet
ArcSet

Reputation: 6860

You can loop the array with a foreach-object and add the folder name.

The | means pipe. It takes the data from the input object and sends it to the next command in the pipe. This case %{} which is a alias for Foreach-Object. You then are storing the output from %{} back into variable $files

$files = @("abc.txt","efg.txt","hij.txt","lmn.txt")

$files = $a | %{
    "FolderName\$_"
}

$files

EDIT : The post was updated with additional information.

So what you need here is a custom object that adds the folder to the name of each file added :

$Files = New-Object PSObject -Property @{
    Array = @()
    FolderName = ""
}
$Files | Add-Member -MemberType scriptmethod  -Name Files -Value {
    param([string]$File = "")
    if($File.Length -eq 0){
        return $this.Array
    }else{
        $this.Array += "$($this.FolderName)\$File"
    }
}


$Files.FolderName = "FolderHere"
$Files.Files("Test.txt")
$Files.Files("Test2.txt")
$Files.Files("Test3.txt")
$Files.Files("Test4.txt")
$Files.Files()

This returns

FolderHere\Test.txt
FolderHere\Test2.txt
FolderHere\Test3.txt
FolderHere\Test4.txt

We are creating a new-object PSObject with the properties FolderName which will store the folder name to add to the files. Array which will hold the final array object. Files which will be a ScriptMethod member that will add the folder to the name and if nothing is entered as a param will return the Array property

Upvotes: 3

Related Questions