我遇到一种情况,我有一个script_1.ps1被用户直接调用。 Script_1.ps1实际上只是script_2.ps1的入口(至少仅提供硬编码的配置值),其中包含共享的,分解后的逻辑。我希望用户能够将任何或所有必需的参数传递给script_1,而后者又必须传递给script_2。如果用户未传递所有必需的参数,则script_2中会有逻辑提示用户输入信息。
在理想的设置中,我将让script_1接受用户的命名参数,然后script_2接受来自script_1的命名参数。例如,我的script_1.ps1看起来像这样:
param (
[switch] $Help = $false,[switch] $Quiet,[string] $Param1,[string] $Param2,[Parameter(Position=0,ValueFromRemainingArguments=$true)] $args
)
if (!$Help) {
.\script_2.ps1 -ServiceName "Service name here" #also pass any other args that were set by user (may be none,several,or all)
}
然后我的script_2.ps1看起来像这样:
param (
[switch] $Quiet,[Alias("l")]
[string] $ServiceName,ValueFromRemainingArguments=$true)] $args
)
# do things with arguments here
当我从script_1.ps1调用script_2.ps1时,是否可以在不枚举所有参数的情况下实现这一目标?我的script_1有大约20个不同的可能参数,所以这样的事情很快就会变得混乱:
.\script_2.ps1 -ServiceName "Service name here" -Quiet $Quiet -Param1 $Param1 -Param2 $Param2
我最接近完成这项工作的是以下内容,但是在到达script_2时,它会用空格切断参数。将转义的引号放在$ args周围不会导致传递任何参数。
param (
[switch] $Help = $false,ValueFromRemainingArguments=$true)] $args
)
if (!$Help) {
Start-Process -FilePath powershell.exe -ArgumentList "-file `".\script_2.ps1`" -ServiceName `"Service name here`" $args"
}
我确定我是作为Powershell的相对较新来的人来完成此操作的窍门... TIA寻求任何帮助!