将命名参数从一个Powershell脚本传递到另一个

我遇到一种情况,我有一个script_1.ps1被用户直接调用。 Script_1.ps1实际上只是script_2.ps1的入口(至少仅提供硬编码的配置值),其中包含共享的,分解后的逻辑。我希望用户能够将任何或所有必需的参数传递给script_1,而后者又必须传递给script_2。如果用户未传递所有必需的参数,则script_2中会有逻辑提示用户输入信息。

在理想的设置中,我将让script_1接受用户的命名参数,然后script_2接受来自script_1的命名参数。例如,我的s​​cript_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寻求任何帮助!

hliyouheng 回答:将命名参数从一个Powershell脚本传递到另一个

您可以使用splatting将参数集合从第一个脚本传递到第二个脚本。这就是说,您无需将参数写到script2.ps1上,而是传递键值对的哈希表。

幸运的是,有一个内置的哈希表,其中已经包含传递给脚本或函数的参数-$PSBoundParameters-因此,您只需将其从script1.ps1向下扩展到{{1} } ...

请注意,您使用script2.ps1符号而不是@-即在这种情况下为$调用“ splat”。

script.ps1

@PSBoundParameters

script2.ps1

param (
    [switch] $Help = $false,[switch] $Quiet,[string] $Param1,[string] $Param2,[Parameter(Position=0,ValueFromRemainingArguments=$true)] $args
)

if (!$Help) {
    write-host "script1.ps1"
    write-host ($PSBoundParameters | ft | out-string);
    . .\script2.ps1 @PSBoundParameters
}

如果您随后致电:

param (    
    [switch] $Quiet,[Alias("l")]
    [string] $ServiceName,ValueFromRemainingArguments=$true)] $args
)

# do things with arguments here
write-host "script2.ps1"
write-host ($PSBoundParameters | ft * | out-string)

您将获得以下输出:

C:\> powershell .\script1.ps1 -Param1 "aaa" -Quiet:$true

,如果您不喜欢内置的script1.ps1 Key Value --- ----- Param1 aaa Quiet True script2.ps1 Key Value --- ----- Param1 aaa Quiet True 哈希表,则可以构建自己的splat并使用splat:

$PSBoundParameters
本文链接:https://www.f2er.com/3164182.html

大家都在问