2013-10-27 2 views
0

개체를 CSV 파일로 내보내려고하지만 마지막 시트 만 저장됩니다. 이유가 무엇입니까?Powershell - CSV로 내보내려고하지만 마지막 레코드 만 가져옵니다.

$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 
+0

그것은 foreach 루프 이전 반복에 의해 저장된 데이터를 덮어 쓰기하고, 마지막 반복이 파일에지고 통해 각각의 반복처럼 보인다. –

+0

어떻게하면 멈출 수 있습니까? – methuselah

답변

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 
0

사용중인 powershell 버전은 무엇입니까? V3 및 V4는 -append을 사용하십시오 :

Export-csv "apps.csv" -Append -NoTypeInformation 
관련 문제