Share via

Powershell : Deep IF ($Var1 = $Set1) statement

Mali Stane 91 Reputation points
2020-10-29T14:47:13.743+00:00

Hi I have a deep IF statement of ten parameter. I need to find a solution to simplified.
If ($Var1 = $Set1) {…}
Else {
If ($Var1 = $Set2) {…}
Else {
If ($Var1 = $Set3) {…}

..
..

Else {
If ($Var1 = $Set10) {…}
}}}}}}}}}}}

Can this be streamline or simplified.
I basically have ten static values and I m verifying if $var1 equal $SetX and then set some other values….
Thank you.

Windows for business | Windows Server | User experience | PowerShell

Answer accepted by question author

  1. Vaibhav Chaudhari 39,006 Reputation points Volunteer Moderator
    2020-10-29T14:54:05.053+00:00

    Try switch statement to see if that works
    Reference - https://powershellexplained.com/2018-01-12-Powershell-switch-statement/?utm_source=blog&utm_medium=blog&utm_content=ifstatement

    $day = 3
    
    switch ( $day )
    {
        0 { $result = 'Sunday'    }
        1 { $result = 'Monday'    }
        2 { $result = 'Tuesday'   }
        3 { $result = 'Wednesday' }
        4 { $result = 'Thursday'  }
        5 { $result = 'Friday'    }
        6 { $result = 'Saturday'  }
    }
    
    $result
    
    # Output
    'Wednesday'
    

    Please don't forget to Accept Answer and Up-vote if the response helped -- Vaibhav

    Was this answer helpful?

    2 people found this answer helpful.
    0 comments No comments

1 additional answer

Sort by: Most helpful
  1. js2010 191 Reputation points
    2020-10-31T21:34:02.037+00:00

    The powershell test for equality is "-eq". "=' is for assignment.

    Was this answer helpful?

    1 person found this answer helpful.
    0 comments No comments

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.