0

I'm trying to export an object to a CSV file but only the last sheet gets saved - any idea why?

$rangeAddr=$startCell_appname + ":" + $endCell_appname
$sh.Range($rangeAddr).Value2 |
  foreach {
    $apps = "" | Select appname,location,lob,os
    $apps.appname = $_ 
    $apps.location = ""   
    $apps.lob = $sh.Name
    $apps.os = "Windows 7"
    $apps
   } | Export-csv "apps.csv" -NoTypeInformation
4

2 回答 2

1

您不能也不想阻止它覆盖。foreach 循环正在创建一系列对象,重用相同的变量。在循环结束时,每个完成的对象都会输出到管道。你只需要从那里拿起它们。

clear all

$before = @(get-process excel | %{$_.Id})
$excel=new-object -com excel.application
$excelId = get-process excel | %{$_.Id} | ?{$before -notcontains $_}
$wb=$excel.workbooks.open("c:\b7.xlsx")

$(for ($i=3; $i -le $wb.sheets.count; $i++){

    $sh=$wb.Sheets.Item($i)
    $startCell_appname = $sh.cells.item(1,2).EntireColumn.find("Application Name").Address()
    $startCell_appname = [regex]::replace($startCell_appname, '(\$\w+\$)(\d+)', {param($m) $m.groups[1].value + ([int]$m.groups[2].value+1)})    

    $endCell_appname = $sh.cells.item(1,2).EntireColumn.find("").Address()
    $endCell_appname = [regex]::replace($endCell_appname, '(\$\w+\$)(\d+)', {param($m) $m.groups[1].value + ([int]$m.groups[2].value-1)})

    # pull data
    $rangeAddr=$startCell_appname + ":" + $endCell_appname
    $sh.Range($rangeAddr).Value2 |
      foreach {
        $apps = "" | Select appname,location,lob,os
        $apps.appname = $_ 
        $apps.location = ""   
        $apps.lob = $sh.Name
        $apps.os = "Windows 7"
        $apps
       } 
}) | Export-csv "apps.csv" -NoTypeInformation

# kill excel process
Stop-Process -Id $excelId -Force -ErrorAction SilentlyContinue
于 2013-10-27T01:39:05.413 回答
0

你用的是什么版本的powershell?对于 V3 和 V4 使用-append

Export-csv "apps.csv" -Append -NoTypeInformation
于 2013-10-28T17:29:06.050 回答