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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5144110/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 01:00:25  来源:igfitidea点击:

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

stringpowershell

提问by M. Dudley

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

回答by Keith Hill

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 notpart of the variable name.

这对于路径特别方便,例如${ProjectDir}Bin\$Config\Images. 但是,如果\变量名后面有一个,就足以让 PowerShell 认为它不是变量名的一部分。

回答by ravikanth

You need to wrap the variable in $()

您需要将变量包装在 $()

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

例如, Write-Host "$($MyVariable)NOSPACES"

回答by Massif

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

但这只是我...

回答by mayursharma

You can also use a back tick `as below:

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

Write-Host "$MyVariable`NOSPACES"

回答by Dheeraj2006

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

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

$Variable2 ='Images'

$Variable2 ='图像'

Write-Output ($Variable1+$Variable2)

写输出($Variable1+$Variable2)

回答by Gavin Burke

Easiest solution: Write-Host $MyVariable"NOSPACES"

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

回答by Peter

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