几个小时后,我需要PS脚本的帮助。

我有一个数组,其中:

computername   Folder  Size
PC1              A      123
PC1              B      18
PC1              C      356
PC2              A      589
PC2              B      58
PC2              C      59
PC2              D      89

我需要以某种方式将列与行交换,结果将如下所示:
         Folder_A   Folder_B  Folder_C  Folder_D
PC1      123        18        356
PC2      589        58         59       89

你能帮我吗?

最佳答案

如果我们假设$array确实包含具有在列中指定的属性的对象数组,则可以执行以下操作:

$output = $array | Group-Object computername | Foreach-Object {
    $hash = [ordered]@{Computer=$_.Name}
    $_.Group | Foreach-Object {
        $hash.Add(('Folder_'+$_.Folder),$_.Size)
    }
    [pscustomobject]$hash
    }
}

$output | Format-List
$output将包含一个对象数组。由于这些对象可能具有不同的属性,因此控制台中可能会出现显示问题。例如,PC1将没有Folder_D,并且由于它是数组中的第一项,因此所有其余对象的默认输出将缺少Folder_D。这就是为什么我添加了Format-List命令的原因,该命令仅用于显示目的,而不能用于进一步处理

关于输出中缺少的列,您有两个选择。一种,您可以将对象排序到列表中具有第一属性的对象。第二,您可以使用其他逻辑来预先确定完整的属性列表,然后将这些属性应用于所有对象。请参阅以下有关预定文件夹列表的信息:
$Folders = $array.Folder | Select -Unique
$output = $array | Group-Object computername | Foreach-Object {
    $hash = [ordered]@{Computer=$_.Name}
    foreach ($Folder in $Folders) {
        $hash.Add(('Folder_'+$Folder),$null)
    }
    $_.Group | Foreach-Object {
        $hash.$('Folder_'+$_.Folder) = $_.Size
    }
    [pscustomobject]$hash

}

$output | Format-Table

关于powershell - 在Powershell中使用行来更改列,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/60488641/

10-13 07:46
查看更多