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

StringPowershell

String Problem Overview


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

String Solutions


Solution 1 - String

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.

Solution 2 - String

You need to wrap the variable in $()

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

Solution 3 - String

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...

Solution 4 - String

You can also use a back tick ` as below:

Write-Host "$MyVariable`NOSPACES"

Solution 5 - String

$Variable1 ='www.google.co.in/'

$Variable2 ='Images'

Write-Output ($Variable1+$Variable2)

Solution 6 - String

Easiest solution: Write-Host $MyVariable"NOSPACES"

Solution 7 - String

if speed matters...

$MyVariable = "Some text"

# slow:
(measure-command {foreach ($i in 1..1MB) {
    $x = "$($MyVariable)NOSPACE"
}}).TotalMilliseconds

# faster:
(measure-command {foreach ($i in 1..1MB) {
    $x = "$MyVariable`NOSPACE"
}}).TotalMilliseconds

# even faster:
(measure-command {foreach ($i in 1..1MB) {
    $x = [string]::Concat($MyVariable, "NOSPACE")
}}).TotalMilliseconds

# fastest:
(measure-command {foreach ($i in 1..1MB) {
    $x = $MyVariable + "NOSPACE"
}}).TotalMilliseconds

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionsourcenouveauView Question on Stackoverflow
Solution 1 - StringKeith HillView Answer on Stackoverflow
Solution 2 - StringravikanthView Answer on Stackoverflow
Solution 3 - StringMassifView Answer on Stackoverflow
Solution 4 - StringmayursharmaView Answer on Stackoverflow
Solution 5 - StringDheerajGView Answer on Stackoverflow
Solution 6 - StringGavin BurkeView Answer on Stackoverflow
Solution 7 - StringCarstenView Answer on Stackoverflow