powershell - Powershell循环写入受密码保护的文件

标签 powershell loops

我正在尝试将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/

相关文章:

PowerShell 更改文件和文件夹的所有者

asp.net - 在 Windows Server 2012 的 Azure 启动任务中安装功能

linux - bash/awk 脚本比较两个不同文件夹中所有文件的内容

javascript - For 循环与用户输入 javascript

perl - 我对 foreach 循环不明白什么?

Java while 循环不限制范围?

c++ - 'auto' 关键字是否知道何时使用 const 迭代器?

json - 在Powershell或VBS中翻译的CURL命令

c# - Azure 数据湖存储基准

powershell - 脚本结束后删除读取主机历史记录