Append content to a variable

Is there a way to append content to a variable in the same way that you can when outputting to a file?

Eg.

$Process = get-process

foreach ( $thing in $Process )
{
$Path = $thing.path | out-file c:\PathList.txt -append
}

$ProcessPath = Get-Content -Path C:\PathList.txt

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.

Try this:

$Process = get-process

$paths = @()

foreach ($thing in $Process)
{
	$paths += $thing.path
}

You could also make a list which gives you better performance, like this:

$Process = get-process

$pathList = New-Object System.Collections.Generic.List[System.String]


foreach ($thing in $Process)
{
	$pathList.Add($thing.path)
}

$paths = $pathList.ToArray()

Also you could add a check if the “$thing.path” not equals a null value so it doesn’t add empty lines to the list, like this:

$Process = get-process

$pathList = New-Object System.Collections.Generic.List[System.String]


foreach ($thing in $Process)
{
	if ($thing.Path -ne $null)
	{
		$pathList.Add($thing.path)
	}
}

$paths = $pathList.ToArray()

The “$paths” array can now be used later on in your script.

/Alexander

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

@Alexander Johansson that is perfect, exactly what I was looking for. Thanks for your help

Yes Dave, that would indeed be a good way. :slight_smile:

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!

/Alexander