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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With