PowerShell allows the output from a branching operation (if, switch, foreach, for, and so on) to be assigned to a variable.
This example assigns a value based on a switch statement when converting a value. The values of the variables at the top are expected to change:
$value = 20
$units = 'TB'
$bytes = switch ($Units) {
'TB' { $value * 1TB }
'GB' { $value * 1GB }
'MB' { $value * 1MB }
default { $value }
}
The same approach may be used when working with a loop, such as foreach. The following example shows a commonly used approach to building an array:
$serviceProcesses = @()
foreach ($service in Get-CimInstance Win32_Service -Filter 'State="Running"') {
$serviceProcesses += Get-Process -Id $service.ProcessId
}
In this example, a new array must be recreated with one extra element...