Powershell 使用params将值传递给while循环中的开关
我正在尝试编写一个位于while循环中的脚本。目标是通过键入test来启动函数。然后可以键入“s”,并将值传递给while循环中的开关Powershell 使用params将值传递给while循环中的开关,powershell,Powershell,我正在尝试编写一个位于while循环中的脚本。目标是通过键入test来启动函数。然后可以键入“s”,并将值传递给while循环中的开关 PS > test PS > s hello hello passed 以下是我迄今为止所做的工作: function test{ [cmdletbinding()] param( [Parameter(ParameterSetName="s", ValueFromPipeline=$true,ValueFromPipelineByProperty
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
这里有几个问题
$s
参数不做任何事情,因为您实际上没有将参数参数传递给测试
switch
中的break
语句是完全冗余的,因为switch
不支持PowerShell中的语句fall-through。假设您想在循环中突破,那么您必须(参见下面的示例)
最后,由于您希望while
循环的每次迭代中的输入由两部分组成(在您的示例中是s
,然后是hello
),因此需要将$x
分为两部分:
$first,$second = $x -split '\s',2
然后切换($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"
}
}
}
}