我有两个 PowerShell 脚本,并在带有 PowerShell Core 的 Linux 上使用它们,并希望将 switch 参数从one.ps1
to 传递给second.ps1
,但是$args
填充为一个字符串,其中包含True
和False
子字符串,它不被 接受second.ps1
,因为它有验证在参数块中。
我该如何更改才能使其正常工作?我知道我可以手动枚举所有的参数second.ps1
并组成一个命令参数字符串,但是考虑到其中的参数太多second.ps1
,有没有更好的方法?
我的脚本如下所示:
# one.ps1
param(
[string][ValidateSet("value1", "value2")]$para1,
[switch]$para3 = $false
)
Write-Host "one.ps1: para1=$para1"
Write-Host "one.ps1: para3=$para3"
Write-Host "args=$args"
pwsh ./second.ps1 $args
第二个.ps1
# second.ps1
param(
[string][ValidateSet("value1", "value2")]$para1="value1",
[string][ValidateSet("value3", "value4")]$para2="value3",
[switch]$para3 = $false,
[switch]$para4 = $false,
[switch]$para5 = $false,
[switch]$para6 = $false,
[switch]$para7 = $false,
[switch]$para8 = $false
)
Write-Host "second.ps1: para1=$para1"
Write-Host "second.ps1: para2=$para2"
Write-Host "second.ps1: para3=$para3"
Write-Host "second.ps1: para4=$para4"
Write-Host "second.ps1: para5=$para5"
Write-Host "second.ps1: para6=$para6"
Write-Host "second.ps1: para7=$para7"
Write-Host "second.ps1: para8=$para8"
这是使用它们的命令
pwsh one.ps1 -para1 value1 -para2 value3 -para3:true -para4:false
错误信息:
one.ps1: para1=value1
one.ps1: para3=True
args=-para2 value3 -para4 False
second.ps1: Cannot validate argument on parameter 'para1'. The argument "False" does not belong to the set "value1,value2" specified by the ValidateSet attribute. Supply an argument that is in the set and then try the command again.