目标是将目录(带有子文件夹(中的所有xls文件转换为txt(unicode(,将txt保存在与原始xls文件相同的位置。 我是这样的,不起作用:
$files = Get-ChildItem D:test*.xls -recurse
Write "Loading Files..."
$Excel = New-Object -ComObject Excel.Application
$Excel.visible = $false
$Excel.DisplayAlerts = $false
ForEach ($file in $files)
{
$WorkBook = $Excel.Workbooks.Open($file.Fullname)
$NewFilepath = $file.Fullname -replace ".{4}$"
$NewFilepath = $NewFilepath + ".txt"
$Workbook.SaveAs($NewFilepath,42)
}
Stop-Process -processname EXCEL
$Excel.Quit()
它给出了 en 例外:
No access to 'FileName.txt'.
At line:13 char:6
+ $Workbook.SaveAs($NewFilepath,42)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : OperationStopped: (:) [], COMException
+ FullyQualifiedErrorId : System.Runtime.InteropServices.COMException
我认为这与您在退出Excel进程之前杀死它的方式有关。 试试这样一种方式:
$files = Get-ChildItem D:test*.xls -recurse
$Excel = New-Object -ComObject Excel.Application
$Excel.visible = $false
$Excel.DisplayAlerts = $false
ForEach ($file in $files) {
Write "Loading File '$($file.Name)'..."
$WorkBook = $Excel.Workbooks.Open($file.Fullname)
$NewFilePath = [System.IO.Path]::ChangeExtension($file.Fullname,".txt")
$Workbook.SaveAs($NewFilepath, 42) # xlUnicodeText
}
# cleanup
$Excel.Quit()
[System.Runtime.Interopservices.Marshal]::ReleaseComObject($WorkBook) | Out-Null
[System.Runtime.Interopservices.Marshal]::ReleaseComObject($Excel) | Out-Null
[System.GC]::Collect()
[System.GC]::WaitForPendingFinalizers()
如您所见,我还更改了使用[System.IO.Path]::ChangeExtension()
方法创建新文件名的方法。如果您必须在某一时刻处理.xlsx
文件,这将使它更容易。
另外,使用后始终释放ComObjects(底部的四行将处理这个问题(