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.

3
  • 1
    As an aside: Write-Host is typically the wrong tool to use, 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 stackoverflow.com/a/50416448/45375 Commented Apr 9, 2020 at 1:54
  • yes, that's actually just the intent, i just add it to make sure i'm getting the correct info that i need. Commented Apr 9, 2020 at 5:54
  • @mklement0, this is at least a Write-Output icebreaker for me! :) Commented Apr 9, 2020 at 6:51

3 Answers 3

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

Sign up to request clarification or add additional context in comments.

4 Comments

hi olaf, is there a way to exclude last record from getting the ','
@Ralph I'm not sure if I know what you mean.
so it now gives me the output of the array. path\text1.txt,path\text2.txt, path\text3.txt etc but the last record also gets path\text12.txt"," which i need removed
does youre array have an empty element as the last one?
1

Another variant,

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

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

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.