Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to execute another powershell script with dynamic path, optional parameter and array parameter?

Tags:

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

The SubScript.ps1 starts off like this:

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

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?

like image 553
mhbuur Avatar asked Sep 15 '25 02:09

mhbuur


1 Answers

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

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

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

like image 130
user4003407 Avatar answered Sep 17 '25 20:09

user4003407