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?
-
1Post your actual code... Help us to help you!CB.– CB.2012-10-18 15:40:34 +00:00Commented 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.EBGreen– EBGreen2012-10-18 15:43:08 +00:00Commented 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 populatedmeeeeeeeeee– meeeeeeeeee2012-10-18 16:06:25 +00:00Commented 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?Keith Hill– Keith Hill2012-10-18 16:09:05 +00:00Commented Oct 18, 2012 at 16:09
Add a comment
|
1 Answer
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