Powershell脚本将数组内容导出到Excel

时间:2018-09-25 11:10:54

标签: powershell

我正在使用以下脚本将结果导出到excel。但是,将其导出到excel时仅得到1行。请让我知道如何实现这一点。  #script

$result = @()

$array = @("testA", "testB", "testC","testD")
$array2 = @("testA1", "testB2", "testC3","testD4")
$tbl = new-object psobject            
$tbl | add-member noteproperty VmName $array
$tbl | add-member noteproperty VMIP $array2
$result += $tbl 

$result|Export-Excel -Path "C:\Users\Empower\Desktop\OMS-Log\test.xlsx"

控制台输出:

VmName                                VMIP                            
------                                      ----                            
{testA, testB, testC, testD}     {testA1, testB2, testC3, testD4}

在Excel中导出结果:

 VmName   VMIP
 testA    testA1

Excel中的必需结果

VmName  VMIP
testA   testA1
testB   testB2
testC   testB3
testD   testB4

1 个答案:

答案 0 :(得分:3)

您正在创建一个具有两个属性的对象(每个属性都是数组)。要导出xlsx文件,您需要具有两个属性的四个对象。有时称为zipping

$array = @("testA", "testB", "testC","testD")
$array2 = @("testA1", "testB2", "testC3","testD4")

$result = [System.Linq.Enumerable]::Zip($array,$array2,[Func[Object, Object, Object[]]]{
    [pscustomobject]@{VmName=$args[0];VMIP=$args[1]}
})

$result | Export-Excel -Path "C:\Users\Empower\Desktop\OMS-Log\test.xlsx"

邮政编码也可以表示为:

$result = for ($i=0; $i -lt ([Math]::Min($array.Count, $array2.Count)); $i++) {
    [pscustomobject]@{VmName=$array[$i];VMIP=$array2[$i]}
}