关于new-object的输出,怎样让四个以上的属性同排输出?


PowerShell交流中心关于new-object的输出,怎样让四个以上的属性同排输出?
0
Arthas Liu asked 8 年 ago

如题,当我新建一个object对象时,如果建立的属性在4个以内,可以同排输出,如下:

$psobject=New-Object psobject
$psobject|Add-Member noteproperty "Name" "Arthas"
$psobject|Add-Member noteproperty "Age" "10"
$psobject|Add-Member noteproperty "Job" "Student"
$psobject|Add-Member noteproperty "Hobby" "Reading"
$psobject


Name   Age Job     Hobby  
----   --- ---     -----  
Arthas 10  Student Reading

但是当我定义的属性超过4个,它就变成纵向输出了,如下:

$psobject=New-Object psobject
$psobject|Add-Member noteproperty "Name" "Arthas"
$psobject|Add-Member noteproperty "Age" "10"
$psobject|Add-Member noteproperty "Job" "Student"
$psobject|Add-Member noteproperty "Hobby" "Reading"
$psobject|Add-Member noteproperty "Pet" "Dog"
$psobject
Name  : Arthas
Age   : 10
Job   : Student
Hobby : Reading
Pet   : Dog

如果添加ft -autosize,可以实现同排输出。

$psobject=New-Object psobject
$psobject|Add-Member noteproperty "Name" "Arthas"
$psobject|Add-Member noteproperty "Age" "10"
$psobject|Add-Member noteproperty "Job" "Student"
$psobject|Add-Member noteproperty "Hobby" "Reading"
$psobject|Add-Member noteproperty "Pet" "Dog"
$psobject|ft -AutoSize
Name   Age Job     Hobby   Pet
----   --- ---     -----   ---
Arthas 10  Student Reading Dog

然而在需要循环输出结果的时候,这样会造成格式的混乱,每输出一次都会输出上面的title,如下:

for($i=0;$i -lt 2;$i++){
$psobject=New-Object psobject
$psobject|Add-Member noteproperty "Name" "Arthas"
$psobject|Add-Member noteproperty "Age" "10"
$psobject|Add-Member noteproperty "Job" "Student"
$psobject|Add-Member noteproperty "Hobby" "Reading"
$psobject|Add-Member noteproperty "Pet" "Dog"
$psobject|ft -AutoSize
}
Name   Age Job     Hobby   Pet
----   --- ---     -----   ---
Arthas 10  Student Reading Dog



Name   Age Job     Hobby   Pet
----   --- ---     -----   ---
Arthas 10  Student Reading Dog

怎样让4个以上的属性可以在循环中同排输出呢?

1 Answers
1
Mooser Lee 管理员 answered 8 年 ago
# 第一种
for($i=0;$i -lt 6;$i++){
$psobject=New-Object psobject
$psobject|Add-Member noteproperty "Name" "Arthas"
$psobject|Add-Member noteproperty "Age" "10"
$psobject|Add-Member noteproperty "Job" "Student"
$psobject|Add-Member noteproperty "Hobby" "Reading"
$psobject|Add-Member noteproperty "Pet" "Dog"
if($i -eq 0){ $psobject | ft -AutoSize }
else { $psobject | ft -AutoSize -HideTableHeaders}

}

#更推荐第二种,先保存结果然后在输出
$result = @()
for($i=0;$i -lt 6;$i++){
$psobject=New-Object psobject
$psobject|Add-Member noteproperty "Name" "Arthas"
$psobject|Add-Member noteproperty "Age" "10"
$psobject|Add-Member noteproperty "Job" "Student"
$psobject|Add-Member noteproperty "Hobby" "Reading"
$psobject|Add-Member noteproperty "Pet" "Dog"
$result += $psobject
}

$result |ft -AutoSize
Arthas Liu replied 8 年 ago

cool!多谢多谢