简体   繁体   中英

Construct a string parameter to function - powershell

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 eg

$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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM