17

I have a foreach loop and use the write-host cmdlet to write to the console. I now wish to write the lines into a variable that will store all of the result from the loop. What is the cmdlet/syntax for this?

4
  • 1
    Post your actual code... Help us to help you! Commented Oct 18, 2012 at 15:40
  • I am going to go out on a limb here and without even seeing the code say that you need to first not use Write-Host. Commented Oct 18, 2012 at 15:43
  • I know write host is incorrect I was just using this to watch the output on screen. However i need to simply change this rather than writing to host append a new line into a variable that will be fully populated Commented Oct 18, 2012 at 16:06
  • 1
    @meeeeeeeeee Do you want each line appended to a single string or do you want an array variable where every line is an element in the array? Commented Oct 18, 2012 at 16:09

1 Answer 1

27

Here are couple of ways to do this. Putting the lines in a single string:

$lines = ''
for ($i=0; $i -lt 10; $i++)
{
    $lines += "The current value of i is $i`n"
}
$lines

Or as an array of strings where each line is a different element in the array:

$lines = @()
for ($i=0; $i -lt 10; $i++)
{
    $lines += "The current value of i is $i"
}
$lines
Sign up to request clarification or add additional context in comments.

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.