1

Im wondering how you can construct a string on the fly as a parameter to a function? Example say I have a function like

function MyFunc
{
    Param
         (
              [Parameter(mandatory=$true)] [string] $myString,
              [Parameter(mandatory=$true)] [int] $myInt
         )

    Write-Host ("Param 1 is {0}" -f $myString)
    Write-Host ("Param 2 is {0}" -f $myInt)


}

How can I call it whilst constructing the first string param on the fly e.g.

$myName = "Casper"
$myInt=7

MyFunc "Name is " + $myName $myInt

Ive tried putting {} around the first "bit" like

MyFunc {Name is " + $myName} $myInt

This then incorrectly prints out

Param 1 is "Name is "+$myName
Param 2 is 7

what I want it to print is

Param 1 is "Name is Casper"
Param 2 is 7

I know a better way of doing this would just be to set up the string first,

$pm1 = "Name is " + $myName

and call function MyFunc $pm1 $myInt

but I am just interested to know how it can be done on the fly as it were. How can I construc the string and pass as first parameter on the function call? Hope thats clear.

Thanks

0

1 Answer 1

2

As a general rule of thumb, you can always nest any complex expression in a separate pipeline using the subexpression operator $(...) or grouping operator (...):

MyCommand $("complex",(Get-Something),"argument","expression" -join '-')

But in your particular case we don't need that - you just need to place the variable expression $myName inside the string literal and PowerShell will automatically evaluate and expand its value:

MyFunc "Name is $myName" $myInt

If the variable expression is to be followed by some characters that would otherwise make up a valid part of the variable path, use curly brackets {} as qualifiers:

MyFunc "Name is ${myName}" $myInt
Sign up to request clarification or add additional context in comments.

1 Comment

Thats perfect thanks. The $() bit is what I needed to know.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.