powershellstring-interpolationvariable-expansion

Using expanding strings as Powershell function parameters


I'm trying to write a function that will print a user-supplied greeting addressed to a user-supplied name. I want to use expanding strings the way I can in this code block:

$Name = "World"  
$Greeting = "Hello, $Name!"
$Greeting

Which successfully prints Hello, World!. However, when I try to pass these strings as parameters to a function like so,

function HelloWorld
{  
    Param ($Greeting, $Name)
    $Greeting
}
HelloWorld("Hello, $Name!", "World")

I get the output

Hello, !  
World  

Upon investigation, Powershell seems to be ignoring $Name in "Hello, $Name!" completely, as running

HelloWorld("Hello, !", "World")

Produces output identical to above. Additionally, it doesn't seem to regard "World" as the value of $Name, since running

function HelloWorld
{  
    Param ($Greeting, $Name)
    $Name
}
HelloWorld("Hello, $Name!", "World")

Produces no output.

Is there a way to get the expanding string to work when passed in as a function parameter?


Solution

  • Your issue occurs because the $Name string replacement is happening outside of the function, before the $Name variable is populated inside of the function.

    You could do something like this instead:

    function HelloWorld
    {  
        Param ($Greeting, $Name)
        $Greeting -replace '\$Name',$Name
    }
    
    HelloWorld -Greeting 'Hello, $Name!' -Name 'World'
    

    By using single quotes, we send the literal greeting of Hello, $Name in and then do the replacement of this string inside the function using -Replace (we have to put a \ before the $ in the string we're replace because $ is a regex special character).