PowerShell循环编写密码保护文件



我正在尝试将Excel文件读取到PowerShell中,打开,密码保护它们并将其写回它们。我可以单独执行此操作,但在循环中脚本失败:

#working individually
$f = ("C:mypathOut Files1234dv.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:mypathOut Filestest.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:mypathOut 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:mypathOut Filestest.xls",$xlNormal,"test")
    $a = $xl.Quit() 
    $a = Release-Ref($ws) 
    $a = Release-Ref($wb) 
    $a = Release-Ref($xl) 
}

对不起,我们找不到1234dv.xlsx。有可能被移动吗? 重命名还是删除?在线:16 char:5 $ wb = $ xl.workbooks.s.open($ ff( ~~~~~~~~~~~~~~~~~~~~~~~~~~ categoryInfo:操作stopped:(:) [],cosxception 完全qualifiedErrid:system.runtime.interopservices.comexception com对象 与其基础RCW分开无法使用。在线:17 char:5 $ a = $ wb.saveas(" c: my path ... ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ categoryInfo:操作stopped:(:) [],无效CompobjectException flutlqualifyErrid:system.runtime.interopservices.invalidcomobjectException

我正在使用的所有四个测试文件重复该错误。

我对PowerShell并不真正熟悉,所以我依靠MS Docs,并且无法密码保护Python中的文件,因此认为这会更容易。我知道这也没有解决密码,而是试图让循环首先工作。任何帮助将不胜感激。谢谢。

您应该使用

$wb = $xl.Workbooks.Open($ff.FullName)

为Excel提供完整的文件路径。否则, $ff是一个fileInfo对象,其中需要字符串(路径(

您的问题略有主题,但不是出于您的意图:

从安全角度使用.xls密码不是安全性,而只是烦恼。

如果您需要安全性,那么我建议您使用允许您加密的Azure信息保护,并仅与需要访问的文件安全共享文件。

您仍然需要创建XLS或.XLSX文件(或此事的任何其他文件(,然后您可以简单地绕过它们:

PS C:>foreach ($file in (Get-ChildItem -Path \server1Docs -Recurse -Force | 
    where {!$_.PSIsContainer} |
    Where-Object {$_.Extension -eq ".xls"})) {
       Protect-RMSFile -File $file.PSPath -InPlace -DoNotPersistEncryptionKey All -TemplateID "e6ee2481-26b9-45e5-b34a-f744eacd53b0" -OwnerEmail "IT@Contoso.com"
}

https://learn.microsoft.com/en-us/powershell/module/azureinformationprotection/protect-rmsfile?view= azureipps

最新更新