您不能也不想阻止它覆盖。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