powershell - 在变量前添加空格

时间:2016-05-29 14:53:53

标签: string powershell variables

我正在努力在变量之前添加空格。我的代码如下所示:

exec

我想看看:

Write-Host "Variable description:        @var1"
Write-Host "Longer variable description: @var2"

结果总是:

Variable description:        Value1
Longer variable description: Value2

我尝试将PadLeft和/或PadRight添加到字符串和/或变量中。它工作,如果我使用其他分隔符而不是" space"。在我使用"空间的那一刻,它被吞噬了#34;。如果我使用"同样的事情会发生' &#34 ;. 有人能告诉我,怎么做这个简单的事情?

谢谢

2 个答案:

答案 0 :(得分:2)

您可以创建自定义对象:

$text1 = "Variable description"
$text2 = "Longer variable description"
$var1 = "Value1"
$var2 = "Value2"

New-Object psobject -Property @{$text1=$var1;$text2=$var2} |fl

给出

Longer variable description : Value2
Variable description        : Value1

答案 1 :(得分:1)

也许您的PowerShell主机正在弄乱白色空间。我无法在cmd.exe或PowerShell ISE中重现这一点

$var1 = "Value1"
$var2 = "Value2"

$shortdesc = "Variable description"
$longdesc = "Longer variable description"

Write-Host $shortdesc $var1.PadLeft(35 - $shortdesc.Length)
Write-Host $longdesc $var2.PadLeft(35 - $longdesc.Length)

输出:

Variable description          Value1
Longer variable description   Value2

您可以使用哈希表,或者如前所述,使用PSObject。

$t = @{
    "Variable description" = $var1
    "Longer variable description" = $var2
    "A really looooooooooooooooooooooong one" = $var2
}

$t | Format-Table Key, Value

输出:

Key                                     Value 
---                                     ----- 
Longer variable description             Value2
A really looooooooooooooooooooooong one Value2
Variable description                    Value1

我的PSVersion:

PS C:\> $psversiontable.PSVersion

Major  Minor  Build  Revision
-----  -----  -----  --------
5      1      14316  1000