You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.18 20:18:26