2

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.

Olaf
  • 4,690
  • 2
  • 15
  • 23
Ralph
  • 33
  • 2
  • 1
    As an aside: [`Write-Host` is typically the wrong tool to use](http://www.jsnover.com/blog/2013/12/07/write-host-considered-harmful/), unless the intent is to write _to the display only_, bypassing the success output stream and with it the ability to send output to other commands, capture it in a variable, redirect it to a file. To output a value, use it _by itself_; e.g., `$value` instead of `Write-Host $value` (or use `Write-Output $value`, though that is rarely needed). See also: the bottom section of https://stackoverflow.com/a/50416448/45375 – mklement0 Apr 09 '20 at 01:54
  • yes, that's actually just the intent, i just add it to make sure i'm getting the correct info that i need. – Ralph Apr 09 '20 at 05:54
  • @mklement0, this is at least a `Write-Output` icebreaker for me! :) – Karthick Ganesan Apr 09 '20 at 06:51

3 Answers3

3

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. ;-)

Olaf
  • 4,690
  • 2
  • 15
  • 23
1

Another variant,

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

@(ForEach ($file in $test) { 
    $path + "\" + $file 
}) -join ", "
Karthick Ganesan
  • 375
  • 4
  • 11
0

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.

IT M
  • 359
  • 1
  • 2
  • 12