简体   繁体   English

在PowerShell中连接一个变量和一个没有空格的字符串文字

[英]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 .这对于${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.但是,如果变量名后面有一个\\ ,则足以让 PowerShell 认为它不是变量名的一部分。

You need to wrap the variable in $()您需要将变量包装在 $()

For example, Write-Host "$($MyVariable)NOSPACES"例如, 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/' $Variable1 ='www.google.co.in/'

$Variable2 ='Images' $Variable2 ='图像'

Write-Output ($Variable1+$Variable2)写输出($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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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