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

如何在PowerShell参数的ValidatePattern验证中搭配使用try/catch?

PowerShell脚本添加传参功能解决方案

修改后完整代码

# 参数声明块必须放在脚本最开头,适配你需要的逗号分隔传参格式
param(
    [Parameter(Position = 0)]
    [ValidatePattern("^\d+$")]
    [int[]]$InputValues = @(88,77,66,55,44,33)
)

try {
    [int]$G1 = $InputValues[0]
    [int]$G2 = $InputValues.Count -ge 2 ? $InputValues[1] : 77
    [int]$G3 = $InputValues.Count -ge 3 ? $InputValues[2] : 66
    [int]$G4 = $InputValues.Count -ge 4 ? $InputValues[3] : 55
    [int]$G5 = $InputValues.Count -ge 5 ? $InputValues[4] : 44
    [int]$G6 = $InputValues.Count -ge 6 ? $InputValues[5] : 33
} catch [System.Management.Automation.ValidationMetadataException] {
    [int]$G1 = 10
} catch {
    Write-Host "Please make sure you are only inputting integers."
    Exit
}

Write-Host $G1 
Write-Host $G2
Write-Host $G3 
Write-Host $G4
Write-Host $G5 
Write-Host $G6

调用方法

直接使用你要求的格式执行即可:

. 'Nameofmyscript.ps1' 80, 80, 80, 90, 100, 100

补充说明

如果习惯使用更通用的空格分隔参数,只需把param块调整为如下写法即可:

param(
    [Parameter(Position = 0)][ValidatePattern("^\d+$")][int]$G1 = 88,
    [Parameter(Position = 1)][int]$G2 = 77,
    [Parameter(Position = 2)][int]$G3 = 66,
    [Parameter(Position = 3)][int]$G4 = 55,
    [Parameter(Position = 4)][int]$G5 = 44,
    [Parameter(Position = 5)][int]$G6 = 33
)

对应调用格式为:

. 'Nameofmyscript.ps1' 80 80 80 90 100 100

两种写法都保留了原有验证逻辑和硬编码默认值,不传参数时会自动使用默认值运行。

内容的提问来源于stack exchange,提问作者Rachel D

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.23 22:54:03