Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Powershell v1: Is it possible to assign the result of a switch statement to a variable?

Is it possible to assign the result of a switch statement to a variable.

For example, instead of:

switch ($Extension) 
    { 
        doc {$Location = "C:\Users\username\Documents\"; break} 
        exe {$Location = "C:\Users\username\Downloads\"; break}
        default {$Location = "C:\Users\username\Desktop\"}
    }

Is it possible to do something similar to:

$Location = 
{
    switch ($Extension) 
    { 
        doc {"C:\Users\username\Documents\"; break} 
        exe {"C:\Users\username\Downloads\"; break}
        default {"C:\Users\username\Desktop\"}
    }
}

Trying the above results in $location containing the entire code block as a String.

like image 692
Taylor Gerring Avatar asked Apr 10 '09 16:04

Taylor Gerring


2 Answers

For V1, I would wrap the switch statement in a function.

function Get-DocumentLocation($Extension)
{
    switch ($Extension) 
    { 
        doc {"C:\Users\username\Documents\"; break} 
        exe {"C:\Users\username\Downloads\"; break}
        default {"C:\Users\username\Desktop\"}
    }
}

$Location = Get-DocumentLocation $extension
like image 62
Steven Murawski Avatar answered Sep 28 '22 09:09

Steven Murawski


Does the following work?

$Location = (switch ($Extension) {
               doc {"C:\Users\username\Documents\"; break}
               exe {"C:\Users\username\Downloads\"; break}
               default {"C:\Users\username\Desktop\"}
             })

Or maybe

$Location = $(switch ($Extension) {
               doc {"C:\Users\username\Documents\"; break}
               exe {"C:\Users\username\Downloads\"; break}
               default {"C:\Users\username\Desktop\"}
             })

Don't have v1 here to test, right now but I think that might work.

like image 31
Joey Avatar answered Sep 28 '22 11:09

Joey