如何在PowerShell中不使用params,通过循环获取用户输入存入数组
实现方案
可以通过do-while循环结合Read-Host命令实现需求,无需使用param()参数块。以下是修改后的完整函数:
function PromptCities { [cmdletbinding()] # 初始化存储输入内容的数组 $inputItems = @() $index = 0 do { # 按指定格式生成输入提示 $userInput = Read-Host "city[$index]" # 仅将非空输入存入数组,并递增索引 if (-not [string]::IsNullOrEmpty($userInput)) { $inputItems += $userInput $index++ } # 输入为空时终止循环 } while (-not [string]::IsNullOrEmpty($userInput)) Write-Host "cities ...." # 若需要查看收集到的内容,可取消下方注释 # $inputItems }
关键说明
- 用
@()初始化空数组$inputItems,用于存储用户的有效输入 do-while循环先执行一次输入操作,再判断终止条件:用户直接回车输入空内容时,循环停止Read-Host "city[$index]"严格匹配示例中的提示格式,索引仅在用户输入有效内容后递增- 使用
[string]::IsNullOrEmpty()判断输入是否为空,避免将空格等无效内容存入数组
内容的提问来源于stack exchange,提问作者Ichigo Kurosaki
相关产品推荐
相关产品推荐

