Search code examples
powershellvariable-expansion

PowerShell string format different behaviour within function


While using powershell I struggle to build up a filename from two variables. When I originally creaded the powershell script, it was working fine. Now I have tried to move some repeatable steps into a function, but the string behaviour is different.

MWE:

$topa = "ABC"
$topb = "XYZ"

function Test-Fun{
    param(
        $a, 
        $b
        )
    echo "$($a)H$($b).csv"
}

echo "$($topa)H$($topb).csv"

Test-Fun($topa, $topb)

The output on my system is

ABCHXYZ.csv
ABC XYZH.csv

Originally, I wanted to use an underscore instead of H and thought that is causing issues, but its not. What did I miss or rather what is the difference between string expansion within a function and outside of it?


Solution

  • You are calling Test-Func wrong. The comma after $topa will create an array, so you basically pass []"ABC", "XYZ" as an array to $a. In that case $b is empty!

    You can easily fix this by removing the comma (also the parentheses are not necessary):

    Test-Fun $topa $topb