2016-12-27 67 views
1

我正在尝试编写一个坐在while循环中的脚本。目标是通过键入test来启动该功能。然后,您可以键入“s”并将值传递给while循环中的开关。使用params在while循环中将值传递给开关

PS > test 
PS > s hello 
hello passed 

这是我迄今所做的:

function test{ 
[cmdletbinding()] 
param(
[Parameter(ParameterSetName="s", ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)][string[]]$s 
) 
while($true){ 
$x = Read-Host 
switch($x){ 
s { 
Write-Host $s "passed" 
break 
} 
default {"False"} 
} 
} 
} 

请让我知道我的逻辑是关闭的。

目前我能够设置x等于s,这里是我得到的。

PS > test 
PS > s 
passed 

回答

3

这里有几个问题。

$s参数不会执行任何操作,因为您实际上没有将参数参数传递给test

switch中的break声明是完全冗余的,因为switch不支持PowerShell中的声明隐藏。假设你想打出来的while循环,你必须label the loop and break statement(见下面的例子)

最后,因为你期望在while循环的每次迭代的输入由两个部分组成(在你的榜样s然后hello),你需要$x分成两个:

$first,$second = $x -split '\s',2 

然后switch($x),所以我们最终是这样的:

function test 
{ 
    [CmdletBinding()] 
    param() 

    # label the while loop "outer" 
    :outer while($true){ 
     $x = Read-Host 

     # split $x into two parts 
     $first,$second = $x -split '\s',2 

     # switch evaluating the first part 
     switch($first){ 
      s { 
       # output second part of input 
       Write-Host $second "passed" 

       # explicitly break out of the "outer" loop 
       break outer 
      } 
      default { 
       Write-Host "False" 
      } 
     } 
    } 
}