我正在尝试将Excel文件读入Powershell,打开,用密码保护它们并将它们写回。我可以单独执行此操作,但在循环内脚本失败:
#working individually
$f = ("C:my\path\Out Files\1234dv.xlsx")
$outfile = $f.FullName + "out"
$xlNormal = -4143
$xl = new-object -comobject excel.application
$xl.Visible = $True
$xl.DisplayAlerts = $False
$wb = $xl.Workbooks.Open($f)
$a = $wb.SaveAs("C:my\path\Out Files\test.xls",$xlNormal,"test")
$a = $xl.Quit()
$a = Release-Ref($ws)
$a = Release-Ref($wb)
$a = Release-Ref($xl)
#not working in loop, error after
function Release-Ref ($ref) {
([System.Runtime.InteropServices.Marshal]::ReleaseComObject(
[System.__ComObject]$ref) -gt 0)
[System.GC]::Collect()
[System.GC]::WaitForPendingFinalizers()
}
foreach ($f in Get-ChildItem "C:\my\path\Out Files"){
$ff = $f
$outfile = $f.FullName + "out"
$xlNormal = -4143
$xl = new-object -comobject excel.application
$xl.Visible = $True
$xl.DisplayAlerts = $False
$wb = $xl.Workbooks.Open($ff)
$a = $wb.SaveAs("C:\my\path\Out Files\test.xls",$xlNormal,"test")
$a = $xl.Quit()
$a = Release-Ref($ws)
$a = Release-Ref($wb)
$a = Release-Ref($xl)
}
Sorry, we couldn't find 1234dv.xlsx. Is it possible it was moved, renamed or deleted? At line:16 char:5 + $wb = $xl.Workbooks.Open($ff) + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : OperationStopped: (:) [], COMException + FullyQualifiedErrorId : System.Runtime.InteropServices.COMException COM object that has been separated from its underlying RCW cannot be used. At line:17 char:5 + $a = $wb.SaveAs("C:\my\path ... + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : OperationStopped: (:) [], InvalidComObjectException + FullyQualifiedErrorId : System.Runtime.InteropServices.InvalidComObjectException
对于正在使用的所有四个测试文件,都会重复出现该错误。
我对Powershell并不是很熟悉,所以我依靠MS docs,并且我不能用密码保护python中的文件,因此认为这样做会更容易。我知道这也不能解决密码,但要先使循环生效。任何帮助将不胜感激。谢谢。
最佳答案
你应该用
$wb = $xl.Workbooks.Open($ff.FullName)
为Excel提供完整的文件路径。否则,
$ff
是一个FileInfo对象,其中需要一个字符串(路径)至于密码保护,我建议this可以为您提供帮助。
关于powershell - Powershell循环写入受密码保护的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55959851/