通常将PowerShell阵列行转换为列

时间:2016-10-27 15:18:43

标签: arrays excel powershell

SO上有quitefew posts来解决PowerShell转置问题。但是,大多数代码都是特定于用例或地址从文本/ CSV文件收集的数据,对我没有好处。我希望看到一个可以在没有这些细节的情况下完成这项工作的解决方案,并直接在PS中使用数组。

示例数据:

Customer Name:    SomeCompany
Abbreviation:    SC
Company Contact:    Some Person
Address:    123 Anywhere St.
ClientID:    XXXX

这个数据要复杂得多,但如果我可以让行和列合作,我可以使用其他方法。数组的东西"名称:"和#34; SomeCompany"是列标题。这是数据收集和无法更改的副产品。我使用PSExcel从Excel电子表格导入数据,电子表格格式无法更改。

期望的输出:

Customer Name:, Abbreviation:, Company Contact:, Address:, ClientID:
SomeCompany, SC, Some Person, 123 Anywhere St., XXXX

我尝试过的事例:

$CustInfo = Import-XLSX -Path "SomePath" -Sheet "SomeSheet" -RowStart 3 -ColumnStart 2
$b = @()
foreach ($Property in $CustInfo.Property | Select -Unique) {
    $Props = [ordered]@{ Property = $Property }
    foreach ($item in $CustInfo."Customer Name:" | Select -Unique){ 
        $Value = ($CustInfo.where({ $_."Customer Name:" -eq $item -and 
                    $_.Property -eq $Property })).Value
        $Props += @{ $item = $Value }
    }
    $b += New-Object -TypeName PSObject -Property $Props
}

这不起作用,因为"其他"我提到的数据。此特定工作簿中还有许多其他部分,因此" Select -Unique"失败而没有错误,输出为空。如果我可以将输入限制为仅选择我需要的行/列,则可能有一个镜头。看来,虽然有一个" RowStart"和#34; ColumnStart"对于Import-XLSX,没有用于停止任何一个的属性。

我已尝试过以上链接的SO问题的方法,但正如我所说,它们要么太具体问题的数据,要么适用于导入CSV文件而不使用数组。

1 个答案:

答案 0 :(得分:0)

我能够通过做两件事来解决这个问题:

  1. 使用" -Header"删除了额外的列。打开Import-XLSX函数以添加伪标题名称,然后只选择那些标题。

    $CustInfo = Import-XLSX -Path "SomePath" -Sheet "SomeSheet" -RowStart 2 -ColumnStart 2 -Header 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18 | Select "1","2"
    
  2. 这样做的缺点是我必须知道输入数据有多少列 - 不是动态的。如果有人能为这个问题提供解决方案,我将不胜感激。

    1. 使用简单的foreach循环翻转列和标题:

      $obj = [PSCustomObject]@{}
      ForEach ($item in $CustInfo) {
         $value = $null
         $name = $null
         if ($item."2") { [string]$value = $item."2" }
         if ($item."1") { [string]$name = $item."1" }
         if ($value -and $name) {
             $obj | Add-Member -NotePropertyName $name -NotePropertyValue $value
         }
      }
      
    2. 我必须在属性名称和值上强制使用字符串类型,因为邮政编码和CustID格式化为Int32。否则,这就是我需要的。

相关问题