Ralph
Ralph

Reputation: 33

Powershell - ForEach statement - concatenate results

I'm hoping to get some help from anyone here regarding powershell scripting.

I'm trying to see if there's a way to call all the results of the ForEach statement:

ForEach ($file in $test) {
        $filepath = $path+"\"+$file
        write-host $filepath
}

the write-host $filepath inside the ForEach statement returns the following:

c:\....\file1.txt
c:\....\file2.txt
c:\....\file3.txt
etc...

i'm trying to see if i can get all those results and put them into 1 line that i can use outside of the foreach statement. sort of like:

c:\....\file1.txt, c:\....\file2.txt, c:\....\file3.txt etc

right now, if i use write-host $filepath outside of the ForEach statement, it only gives me the last result that $filepath got.

hope i made sense.

thank you in advance.

Upvotes: 2

Views: 1082

Answers (3)

IT M
IT M

Reputation: 447

You might also want to get a look at the FullName property of Get-ChildItem.

If you do (gci).FullName (or maybe gci | select FullName) you'll directly get the full path.

So if $test is a gci from C:\some\dir, then $test.FullName is the array you are looking for.

Upvotes: 0

Karthick Ganesan
Karthick Ganesan

Reputation: 385

Another variant,

$path = $pwd.Path   # change as needed
$test = gci         # change as needed

@(ForEach ($file in $test) { 
    $path + "\" + $file 
}) -join ", "

Upvotes: 1

Olaf
Olaf

Reputation: 5232

Nothing easier than that ... ;-)

$FullPathList = ForEach ($file in $test) {
    Join-Path -Path $path -ChildPath $file
}
$FullPathList -join ','

First you create an array with the full paths, then you join them with the -join statement. ;-)

Upvotes: 3

Related Questions