Welcome › Forums › General PowerShell Q&A › Replacing IF statements with a SWITCH statement
- This topic has 3 replies, 3 voices, and was last updated 4 months ago by
Participant.
Viewing 3 reply threads
-
AuthorPosts
-
-
September 11, 2020 at 12:09 pm #255881
Hi,
I’ve created the below script as part of a training exercise to improve my PowerShell skills. It works as expected but could do with some advice on how to replace the IF statements with a switch statement.
PowerShell12345678910111213141516171819202122232425262728293031323334Function Get-LocalProcesses {# Default to SortByName[CmdletBinding(DefaultParameterSetName = 'SortByName')]Param ([Parameter(ParameterSetName = 'SortByCPU')][switch]$SortByCPU,[Parameter(ParameterSetName = 'SortByRAM')][switch]$SortByRAM,[Parameter(ParameterSetName = 'SortByName')][switch]$SortByName,[int]$ShowFirst = '5')# Outputs which parameter is being used with the command$PSCmdlet.ParameterSetName# Set sort variable depending on switch usedIf ($SortByCPU) {$SortChoice = 'cpu'}If ($SortByRAM) {$SortChoice = 'ws'}If ($SortByName) {$SortChoice = 'name'}# Get local processes using chosen switch in sort cmdletGet-Process | Sort-Object $SortChoice | Select-Object Id, Handles, @{Label = 'WS(k)'; Expression = { ($_.ws / 1024) } }, @{Label = 'CPU(m)'; Expression = { ($_.cpu).tostring("#.##") } }, @{Label = 'Priority'; Expression = { ($_.Priorityclass) } }, Name, Description -First $ShowFirst | FT -AutoSize}Get-LocalProcesses -SortByRAMAny advice would be very much appreciated.
Cheers
Jamie
-
This topic was modified 4 months, 1 week ago by
kvprasoon. Reason: code formatting
-
This topic was modified 4 months, 1 week ago by
-
September 11, 2020 at 1:23 pm #255893
As you use Powershell cmdlets, pay attention to how they are named and the parameter names and how they are used.
- Singular – Notice how cmdlets are named singular (e.g Get-User, Get-Service, Get-Process), not Get-Processes
- Function Purpose – For what you are doing, the function should just return data. Get-Data | Sort-Data. If you look at other cmdlets, they don’t have sort capabilities because the goal of the function should be just to get the data, so you would normally have filter capabilities in a GET cmdlet\function.
- Switch – In your case, a switch statement isn’t applicable. Typically a switch compares the same variable and executes a code block based on different values. If we wanted to check $Name and if it’s John, Sue or Sam then do something. In this case, you have three separate variables.
- Parameter Names – Leveraging Select-Object with a First param, try to follow the same naming schema (i.e. First vs. ShowFirst) so that it’s consisten. Anyone that has used First will know what the purpose of the switch is. If you still want to use ShowFirst, then you should set the variable to First and use an Alias for Show First.
A better approach would be to use a validateset to show the possible sort options:
PowerShell123456789101112131415161718Function Get-LocalProcess {[CmdletBinding()]param ([Parameter(Mandatory=$false)][ValidateSet('CPU','RAM','Name')][string]$SortBy = 'Name',[Parameter(Mandatory=$true)][Alias('ShowFirst')][int]$First = '5')Write-Verbose -Message ('Sorting on {0}' -f $SortBy)Get-Process |Sort-Object $SortBy |Select-Object -First $First}Get-LocalProcess -ShowFirst 3 -SortBy RAM -Verbose -
September 11, 2020 at 3:22 pm #255944
You can turn your if statement block into switch statements using your parameter sets.
PowerShell12345switch ($PSCmdlet.ParameterSetName) {'SortByCPU' { $sortchoice = 'cpu' }'SortByRam' { $sortchoice = 'ws' }default { $sortchoice = 'name' }} -
September 14, 2020 at 12:12 pm #256490
Sorted it (Pardon the pun)…..
PowerShell1234switch ($PSCmdlet.ParameterSetName) {`'SortByCPU' { $SortChoice = @{expression = 'cpu';descending = $true} }'SortByRam' { $SortChoice = @{expression = 'ws';descending = $true} }default { $SortChoice = @{expression = 'name';descending = $false} }Thanks for the help with all the other bits.
Cheers
JamiePowerShell1-
This reply was modified 4 months ago by
jshizzle14.
-
This reply was modified 4 months ago by
jshizzle14.
-
This reply was modified 4 months ago by
-
-
AuthorPosts
Viewing 3 reply threads
- The topic ‘Replacing IF statements with a SWITCH statement’ is closed to new replies.