Replacing IF statements with a SWITCH statement

Welcome Forums General PowerShell Q&A Replacing IF statements with a SWITCH statement

Viewing 3 reply threads
  • Author
    Posts
    • #255881
      Participant
      Topics: 1
      Replies: 3
      Points: 15
      Rank: Member

      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.

      Any advice would be very much appreciated.

      Cheers

      Jamie

      • This topic was modified 2 weeks ago by kvprasoon. Reason: code formatting
    • #255893
      Participant
      Topics: 15
      Replies: 1775
      Points: 3,214
      Helping Hand
      Rank: Community Hero

      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:

    • #255944
      Participant
      Topics: 0
      Replies: 81
      Points: 362
      Helping Hand
      Rank: Contributor

      You can turn your if statement block into switch statements using your parameter sets.

    • #256490
      Participant
      Topics: 1
      Replies: 3
      Points: 15
      Rank: Member

      Sorted it (Pardon the pun)…..

      Thanks for the help with all the other bits.

      Cheers
      Jamie

      • This reply was modified 1 week, 4 days ago by jshizzle14.
      • This reply was modified 1 week, 4 days ago by jshizzle14.
Viewing 3 reply threads
  • You must be logged in to reply to this topic.