将“Write-Host”与变量对齐

时间:2012-12-10 00:37:03

标签: powershell powershell-v2.0

这是我的代码:

Write-Host "Field 1 : " $variable1  
Write-Host "Field 2 : " $variable2
Write-Host "Field 3 : " $variable3
Write-Host "Field 4 : " $variable4

我得到的输出如下:

   Field 1    : " $variable1    
   Field 2          : " $variable2
   Field 3      : " $variable3
   Field 4           : " $variable4

如何对齐它们?

由于

1 个答案:

答案 0 :(得分:4)

我认为,基于他先前的问题,field1,2,3 ...是具有可变长度的db字段名称。

第一个解决方案,不是很优雅,但您可以使用-f格式运算符添加一些额外的空格来对齐第二列(下面我们使用40个字符减去第一列的长度)

$field1=@("name";"username1")
$field2=@("age";24)
$field3=@("email";"you@there.com")

wh $field1[0] " : " $field1[1] 
wh $field2[0] " : " $field2[1]
wh $field3[0] " : " $field3[1]

wh

#fill some extra whitespaces 
$spaces1=40 - $field1[0].Length
$spaces2=40 - $field2[0].Length
$spaces3=40 - $field3[0].Length
"{0}{1,$spaces1}" -f $field1[0], " : "+$field1[1]
"{0}{1,$spaces2}" -f $field2[0], " : "+$field2[1]
"{0}{1,$spaces3}" -f $field3[0], " : "+$field3[1]

结果

name  :  username1
age  :  24
email  :  you@there.com

name                                  : username1
age                                   : 24
email                                 : you@there.com

第二个解决方案

如果您创建了pscustom对象,那么您可以使用所有那些花哨的cmdlet,例如format-table :):

$col=@(
[PSCustomObject]@{$field1[0]=$field1[1]},
[PSCustomObject]@{$field2[0]=$field2[1]},
[PSCustomObject]@{$field3[0]=$field3[1]}
)

$col |ft

结果:

Name                           Value                                                                                 
----                           -----                                                                                 
name                           username1                                                                             
age                            24                                                                                    
email                          you@there.com