[英]Concatenating a variable and a string literal without a space in PowerShell
如何在沒有空格的情況下將變量寫入控制台? 我嘗試時出現問題:
$MyVariable = "Some text"
Write-Host "$MyVariableNOSPACES"
我想要以下輸出:
Some textNOSPACES
另一種選擇,可能是更規范的方法是使用花括號來描述名稱:
$MyVariable = "Some text"
Write-Host "${MyVariable}NOSPACES"
這對於${ProjectDir}Bin\\$Config\\Images
路徑特別方便。 但是,如果變量名后面有一個\\
,則足以讓 PowerShell 認為它不是變量名的一部分。
您需要將變量包裝在 $()
例如, Write-Host "$($MyVariable)NOSPACES"
Write-Host $MyVariable"NOSPACES"
會工作,雖然它看起來很奇怪......我會去:
Write-Host ("{0}NOSPACES" -f $MyVariable)
但這只是我...
您還可以使用反勾號`
,如下所示:
Write-Host "$MyVariable`NOSPACES"
$Variable1 ='www.google.co.in/'
$Variable2 ='圖像'
寫輸出($Variable1+$Variable2)
最簡單的解決方案: Write-Host $MyVariable"NOSPACES"
如果速度很重要...
$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.