Search code examples
stringpowershellstring-concatenation

PowerShell string concatenation behaves differently inside vs. outside a function


I'm seeing really odd behavior in string concatenation in PowerShell. At first I was using "$var1: Hello" syntax for string replacement, but then switched to simple concatenation with + because it wasn't working. Now I'm noticing that using the exact same assignment expression, I get two different results.

This feels buggy to me, but I want to make sure I'm not doing something wrong.

function Test-Diff([string] $sRepoGUID, [string] $sChangeset1, [string] $sChangeset2){
  $url = $g_backendUrl + "repo/" + $sRepoGUID + "/diff/" + $sChangeset1 + ":" + $sChangeset2 + "?format=json&ignorews=True&maxsize=100000&timeout=10"
  Write-Output $url
}

$g_backendUrl = "http://localhost:56783/"
$sRepoGUID = '34CAA433-1600-469E-95B7-35CA0A0FECF4'
$sChangeset1 = '9d21e91b213a07e56d16a9b8fe519ad570d5c46e'
$sChangeset2 = '68269169cdd0b803d0e419752ce9cae627e589e5'
$url = $g_backendUrl + "repo/" + $sRepoGUID + "/diff/" + $sChangeset1 + ":" + $sChangeset2 + "?format=json&ignorews=True&maxsize=100000&timeout=10" 
Write-Output $url
Test-Diff($sRepoGUID, $sChangeset1, $sChangeset2)

That writes the following to the console:

http://localhost:56783/repo/34CAA433-1600-469E-95B7-35CA0A0FECF4/diff/9d21e91b213a07e56d16a9b8fe519ad570d5c46e:68269169cdd0b803d0e419752ce9cae627e589e5?format=json&ignorews=True&maxsize=100000&timeout=10
http://localhost:56783/repo/34CAA433-1600-469E-95B7-35CA0A0FECF4 9d21e91b213a07e56d16a9b8fe519ad570d5c46e 68269169cdd0b803d0e419752ce9cae627e589e5/diff/:?format=json&ignorews=True&maxsize=100000&timeout=10

Note how the first string contains /diff/ and : in the correct place in the string. The second string has spaces where /diff/ and : should be and instead appends /diff/ and : after the last concatenated variable.

I used the exact same $url = ... expression in both places (I even used copy/paste to be sure).

I'm on Windows 7 x64 and have tested this on two different machines.

What might be happening to cause this behavior?


Solution

  • I think the problem is in the way you're passing arguments to your function. See if this works better:

    Test-Diff $sRepoGUID $sChangeset1 $sChangeset2