简体   繁体   English

Powershell v1:是否可以将switch语句的结果赋给变量?

[英]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. 是否可以将switch语句的结果赋给变量。

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. 尝试上面的结果将$ location包含整个代码块作为String。

For V1, I would wrap the switch statement in a function. 对于V1,我将switch语句包装在一个函数中。

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

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. 现在没有v1在这里进行测试,但我认为这可能有用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM