Is there a way to keep adding content to a variable while the foreach loop is running? The aim would be to have a variable containing data that could then be used for other purposes. It works by outputting to a text file but seems a bit messy.
Another high-performance alternative is to just assign the output of your foreach loop to a variable, and let PowerShell worry about building the array:
$Process = get-process
$paths = foreach ($thing in $Process)
{
$thing.Path
}
# For this simple example, this could also be written as:
$paths = $Process | Select-Object -ExpandProperty Path
# Or, in PowerShell 3.0 or later, simply:
$paths = $Process.Path
I didn’t add that in my answer though since this was included in the question "Is there a way to keep adding content to a variable while the foreach loop is running? "
Nick Chard, if that solution is applicable you should consider using that since it’s shorter and faster!