Branching and assignment

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 (and the old copied) for every iteration of the loop.

This operation may be simplified by moving the assignment operation in front of foreach:

$serviceProcesses = foreach ($service in Get-CimInstance Win32_Service -Filter 'State="Running"') {
Get-Process -Id $service.ProcessId
}

In this case, the assignment occurs once when the loop finishes running. There is no array to continually resize.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.191.135.224