简体   繁体   中英

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

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 eg ${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...

您还可以使用反勾号` ,如下所示:

Write-Host "$MyVariable`NOSPACES"

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

$Variable2 ='Images'

Write-Output ($Variable1+$Variable2)

最简单的解决方案: Write-Host $MyVariable"NOSPACES"

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM