sourcenouveau
sourcenouveau

Reputation: 30554

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

Upvotes: 64

Views: 100583

Answers (7)

DheerajG
DheerajG

Reputation: 107

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

$Variable2 ='Images'

Write-Output ($Variable1+$Variable2)

Upvotes: 3

Keith Hill
Keith Hill

Reputation: 202072

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.

Upvotes: 89

Gavin Burke
Gavin Burke

Reputation: 149

Easiest solution: Write-Host $MyVariable"NOSPACES"

Upvotes: 1

Carsten
Carsten

Reputation: 2211

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

Upvotes: 0

mayursharma
mayursharma

Reputation: 158

You can also use a back tick ` as below:

Write-Host "$MyVariable`NOSPACES"

Upvotes: 4

Massif
Massif

Reputation: 4433

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

Upvotes: 14

ravikanth
ravikanth

Reputation: 25840

You need to wrap the variable in $()

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

Upvotes: 29

Related Questions