PowerShell:如何在循环中更改表头?

3
我希望能够通过xml文件远程收集数据,并稍后根据需要调整表头。这应该在一个循环中发生,看起来像这样:
foreach($tableheader in $table) {
  $table.$tableheader = $xmlFile.$tableheader
}

我尝试了以下几种方法:

$x = 0
$sitesonfig = Get-ConfigSite -AdminAddress localhost  
foreach($Prop in ($siteconfig |get-member -MemberType Property | select -Property name))
{
 $x += 1; 
 $siteconfig = $siteconfig | Select-Object  * | format-table @{l="Smile$x";e={$_.$Prop}}
}

是的,我知道这看起来很傻,但我真的不知道如何逐个更改标题而不必每次列出所有其他标题。

1个回答

0
一种可能性是使用循环来创建标题映射表,然后将其传递给 Format-Table 函数。
以下是您的第二个示例,已修改以演示此概念。您应该能够根据需要从 XML 文件中获取标题信息并应用它。
$x = 0
$siteconfig = Get-ConfigSite -AdminAddress localhost  

$headerMap = @()
foreach($Prop in ($siteconfig |get-member -MemberType Property | select -ExpandProperty name))
{
 $x += 1; 
 $headerMap += @{
        l="Smile$x";
        e={ $_.$Prop }.GetNewClosure()
    }
}
$siteconfig | Format-Table $headerMap

重要要点

  1. Select -Property name 需要改为 Select -ExpandProperty name。原因是在 PowerShell 中,Select-Object 会返回一个经过筛选的对象,但你需要一个字符串来通过名称获取属性值。而 -ExpandProperty 参数将展开为字符串值。
  2. 表达式块需要调用 GetNewClosure() 来捕获 $Prop 在脚本块创建时的值,而不是在调用时的值。如果你对闭包的概念和 PowerShell 的作用域规则还不熟悉,这可能会有点困惑。如果没有这个操作,由于 PowerShell 的作用域规则,$Prop 将在被 Format-Table 使用时评估为当时的值。通过调用 GetNewClosure(),我们可以在调用 GetNewClosure() 时捕获 $Prop 的值,这正是我们在这种情况下所希望的。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接