Welcome › Forums › General PowerShell Q&A › Question about Best Practice – IfElse or Switch
- This topic has 4 replies, 3 voices, and was last updated 5 months, 4 weeks ago by
Participant.
-
AuthorPosts
-
-
July 27, 2020 at 2:39 pm #245141
Wanting to basically have “options” within a script. If a user is a member of a specific OU (based on their distinguished name) do this task. If they are a member of another OU, do a separate (but nearly identical thing).
I’ve seen some mention using an ElseIf combination but I’ve seen elsewhere that people suggest using Switches. I’m honestly not super familiar with loops and even less so with switches. Anyone have any input/suggestions?
PowerShell123456Basic idea:If OU = ABC then grab attribute value and place it in ABCtxt documentelseIf OU = DEF then grab attribute value and place it in DEFtxt documentelseIf OU = JKL then grab attribute value and place it in JKLtxt documentetc..
-
This topic was modified 5 months, 4 weeks ago by
ALombardi01. Reason: typo
-
This topic was modified 5 months, 4 weeks ago by
-
July 27, 2020 at 2:53 pm #245159
If you are comparing the same variable, then you should use switch:
PowerShell123456789101112$ous = 'CN=Marketing,DC=child,DC=company,DC=com','CN=Sales,DC=child,DC=company,DC=com','CN=Foo,DC=child,DC=company,DC=com'foreach ($ou in $ous) {switch -wildcard ($ou) {'*Sales*' {'Doing stuff for Sales'}'*Marketing*' {'Doing stuff for Marketing'}default {'Doing default stuff because the OU {0} is not defined above' -f $_}}}Output:
PowerShell123Doing stuff for MarketingDoing stuff for SalesDoing default stuff because the OU CN=Foo,DC=child,DC=company,DC=com is not defined abovePersonally rarely use ElseIf logic in Powershell.
-
July 27, 2020 at 2:54 pm #245162
I like to use a Switch for this type of thing
PowerShell12345678910<div><div>$ou = 'z4r'</div><div>switch ($ou)</div><div>{</div><div> {$_ -eq 'xyz'} {$Text = 'abc'}</div><div> {$_ -eq '123'} {$Text = 'jkf'}</div><div> {$_ -eq 'abc'} {$Text = 'lmp'}</div><div> {$_ -eq 'z4r'} {$Text = 'rst'}</div><div>}</div><div></div></div>-
This reply was modified 5 months, 4 weeks ago by
Iain.
-
This reply was modified 5 months, 4 weeks ago by
-
July 27, 2020 at 3:02 pm #245168
@Iain
The script block is unnecessary as -eq is the default:
PowerShell123456789$ou = 'z4r'switch ($ou){'xyz' {$Text = 'abc'}'123' {$Text = 'jkf'}'abc' {$Text = 'lmp'}'z4r' {$Text = 'rst'}} -
July 27, 2020 at 3:16 pm #245181
Thanks to both of you, @Iain and @Rob
-
-
AuthorPosts
- The topic ‘Question about Best Practice – IfElse or Switch’ is closed to new replies.