如何使用动态路径、可选参数和数组参数执行另一个 powershell 脚本? [英] How to execute another powershell script with dynamic path, optional parameter and array parameter?

查看:20
本文介绍了如何使用动态路径、可选参数和数组参数执行另一个 powershell 脚本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从一个主要的 PowerShell 脚本调用另一个带有可选参数和另一个非可选字符串数组参数的 PowerShell 脚本.像这样的事情(出于解释原因包括功能失调的呼叫):

From a main PowerShell script I want to call another PowerShell script with an optional parameter and another non optional string array parameter. Something like this (with the dysfunctional call included for explanatory reasons):

$theOptionalParam = "maybe"
$theArrayParam = "A", "B"
$theDirectory = "SomeRelativePath"

#This is the part not working:
.\$theDirectory\SubScript.ps1 -OptionalParam $theOptionalParam -ArrayParam $theArrayParam

SubScript.ps1 是这样开始的:

The SubScript.ps1 starts off like this:

[CmdletBinding()]
Param(
   [Parameter(Mandatory=$false)][string]$OptionalParam,
   [Parameter(Mandatory=$true)][string[]]$ArrayParam
)

但是无论我尝试什么,我都会得到一个错误或者只是数组的第一个值(A"),其余的都被丢弃了.

But no matter what I try, I get an error or simply the first value of the array ("A") and the rest is discarded.

如何同时使用动态路径、可选参数和数组参数正确执行下标?

How do I execute the subscript correct with both the dynamic path, optional parameter and array parameter?

推荐答案

.\$theDirectory\SubScript.ps1 解释为可扩展字符串和 $theDirectory 的扩展值变量,您应该使用调用运算符 &.

To interpret .\$theDirectory\SubScript.ps1 as expandable string and expand value of $theDirectory variable, you should use invoke operator &.

& .\$theDirectory\SubScript.ps1 -OptionalParam $theOptionalParam -ArrayParam $theArrayParam

您可以通过查看解析后的 AST 来看到这一点:

You can see that by looking at parsed AST:

{& .\$theDirectory\SubScript.ps1 -OptionalParam $theOptionalParam -ArrayParam $theArrayParam}.
Ast.EndBlock.Statements[0].PipelineElements[0].CommandElements[0].GetType().Name
# ExpandableStringExpressionAst
{.\$theDirectory\SubScript.ps1 -OptionalParam $theOptionalParam -ArrayParam $theArrayParam}.
Ast.EndBlock.Statements[0].PipelineElements[0].CommandElements[0].GetType().Name
# StringConstantExpressionAst

如您所见,如果不使用 & 调用运算符,则 .\$theDirectory\SubScript.ps1 会被解释为常量字符串,而不是可扩展字符串.

As you can see, if you does not use & invoke operator, then .\$theDirectory\SubScript.ps1 interpreted as constant string, not as expandable string.

这篇关于如何使用动态路径、可选参数和数组参数执行另一个 powershell 脚本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆