Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

People also ask

How do I concatenate a variable and a string in PowerShell?

In PowerShell, string concatenation is primarily achieved by using the “+” operator. There are also other ways like enclosing the strings inside double quotes, using a join operator, or using the -f operator. $str1="My name is vignesh."

How do you concatenate strings and variables?

In JavaScript, we can assign strings to a variable and use concatenation to combine the variable to another string. To concatenate a string, you add a plus sign+ between the strings or string variables you want to connect.


Another option and possibly the more 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.


You need to wrap the variable in $()

For example, Write-Host "$($MyVariable)NOSPACES"


Write-Host $MyVariable"NOSPACES"

Will work, although it looks very odd... I'd go for:

Write-Host ("{0}NOSPACES" -f $MyVariable)

But that's just me...


You can also use a back tick ` as below:

Write-Host "$MyVariable`NOSPACES"