Search code examples
stringpowershell

Concatenating a variable and a string literal without a space in PowerShell


How can I write a variable to the console without a space after it? There are problems when I try:

$MyVariable = "Some text"
Write-Host "$MyVariableNOSPACES"

I'd like the following output:

Some textNOSPACES

Solution

  • One possibly canonical way is to use curly braces to delineate the name:

    $MyVariable = "Some text"
    Write-Host "${MyVariable}NOSPACES"
    

    This is particular handy for paths e.g. ${ProjectDir}Bin\$Config\Images. However, if there is a \ after the variable name, that is enough for PowerShell to consider that not part of the variable name.