gpt4 book ai didi

powershell - 在使用参数集名称的同时使用$ args

转载 作者:行者123 更新时间:2023-12-03 00:45:23 28 4
gpt4 key购买 nike

考虑以下玩具示例脚本test.ps1:

Param(
[Parameter(ParameterSetName='readfile',Position=0,Mandatory=$True)]
[string] $FileName,

[Parameter(ParameterSetName='arg_pass',Mandatory=$True)]
[switch] $Ping
)

if ($Ping.isPresent) {
&$env:ComSpec /c ping $args
} else {
Get-Content $FileName
}

理想的效果是
.\test.ps1 FILE.TXT

显示 FILE.TXT的内容并
.\test.ps1 -Ping -n 5 127.0.0.1

ping本地主机5次。

不幸的是,后者由于错误而失败

找不到与参数名称“n”匹配的参数。
在线:1个字符:18个
+。\ test.ps1 -Ping -n 5 127.0.0.1
+ ~~
+ CategoryInfo:InvalidArgument:(:) [test.ps1],ParameterBindingException
+ FullyQualifiedErrorId:NamedParameterNotFound,test.ps1

当然,这只是一个最小的例子。

通常,我正在寻找一种方法来将 [switch]参数引入脚本中,该脚本位于自己的参数集中,当存在该开关时,我想使用命令行中所有剩余的参数并将其传递给另一个命令行应用程序。在PowerShell中执行此操作的方式是什么?

最佳答案

您可以使用ValueFromRemainingArguments参数属性。我还建议在CmdletBinding中指定默认参数集名称。例:

[CmdletBinding(DefaultParameterSetName="readfile")]
param(
[parameter(ParameterSetName="readfile",Position=0,Mandatory=$true)]
[String] $FileName,
[parameter(ParameterSetName="arg_pass",Mandatory=$true)]
[Switch] $Ping,
[parameter(ParameterSetName="arg_pass",ValueFromRemainingArguments=$true)]
$RemainingArgs
)
if ( $Ping ) {
ping $RemainingArgs
}
else {
Get-Content $FileName
}

(此外:我看不到需要 & $env:ComSpec /c。您可以在PowerShell中运行命令而无需生成cmd.exe副本。)

关于powershell - 在使用参数集名称的同时使用$ args,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48646331/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com