Home > database >  Construct a string parameter to function - powershell
Construct a string parameter to function - powershell

Time:04-21

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

CodePudding user response:

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
  • Related