Domanda

I'm a total noob to PS and I'm having trouble trying to save a folder of CSV files to XLS or XLSX. I can do it for a single file, but can't work out what I'm doing wrong to do it multiple times.

CLS
$path = "H:\My Documents\"
$files = Get-ChildItem $path -include *.csv -recurse
echo $files
foreach($file in $files) {
$objExcel=New-Object -com "Excel.Application" 
$objWorkbook=$objExcel.workbooks.open($file)
$objWorksheet=$objWorkbook.Worksheets.Item(1)

#insert COUNTIF formula into cell A8
$strFormula = "=COUNTIF(I6:I1000," + [char](34) + ">0" + [char](34) + ")"
$objExcel.Cells.Item(1, 8).Formula = $strFormula

#Save as XLS
$xlout=$file.Replace('.csv','xlsx') 
$objWorkbook.SaveAs($xlOut,51) 

$objWorkbook.Close()
$objExcel.Quit()
[System.Runtime.Interopservices.Marshal]::ReleaseComObject($objExcel)
}

Can someone help me please?

È stato utile?

Soluzione

Well, I don't see anything fundamentally wrong, but it may be having issues with Excel opening and closing in rapid succession. Try moving your loop to within the time frame of opening and closing Excel.

CLS
$path = "H:\My Documents\"
$files = Get-ChildItem $path -include *.csv -recurse
echo $files
$objExcel=New-Object -com "Excel.Application" 
foreach($file in $files) {
    $objWorkbook=$objExcel.workbooks.open($file)
    $objWorksheet=$objWorkbook.Worksheets.Item(1)

    #insert COUNTIF formula into cell A8
    $strFormula = "=COUNTIF(I6:I1000," + [char](34) + ">0" + [char](34) + ")"
    $objExcel.Cells.Item(1, 8).Formula = $strFormula

    #Save as XLS
    $xlout=$file.FullName.Replace('.csv','.xlsx') 
    $objWorkbook.SaveAs($xlOut,51) 

    $objWorkbook.Close()
}
$objExcel.Quit()
[System.Runtime.Interopservices.Marshal]::ReleaseComObject($objExcel)

Edit:
I updated $xlout to pull the FullName element, and also fixed it's replacement since it was losing the . and basically changing "somefile.csv" into "somefilexlsx".

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top