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

时间:2019-05-02 20:32:40

标签: 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) 
}
  

对不起,我们找不到1234dv.xlsx。它可能被移动了吗?   重命名或删除?在线:16字符:5   + $ wb = $ xl.Workbooks.Open($ ff)   + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~       + CategoryInfo:OperationStopped:(:) [],COMException       + FullyQualifiedErrorId:System.Runtime.InteropServices.COMException已添加的COM对象   与其下层RCW分开使用。在线:17字符:5   + $ a = $ wb.SaveAs(“ C:\ my \ path ...   + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~       + CategoryInfo:OperationStopped:(:) [],InvalidComObjectException       + FullyQualifiedErrorId:System.Runtime.InteropServices.InvalidComObjectException

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

我对Powershell并不是很熟悉,所以我依靠MS docs,并且我无法用密码对python中的文件进行保护,因此认为这样做会更容易。我知道这也不能解决密码,但要先使循环生效。任何帮助将不胜感激。谢谢。

2 个答案:

答案 0 :(得分:2)

您应该使用

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

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

关于密码保护,我建议this可以为您提供帮助。

答案 1 :(得分:2)

为您的问题而设的主题,但并非出于您的意图:

从安全角度来看,使用.xls密码不是安全性,只是烦人。

它需要安全性,然后建议您使用Azure信息保护之类的工具,该技术可让您加密,并仅与需要访问的用户安全地共享文件。

您仍然需要创建xls或.xlsx文件(或与此相关的任何其他文件) 那么您可以通过Powershell轻松地将它们循环:

PS C:\>foreach ($file in (Get-ChildItem -Path \\server1\Docs -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://docs.microsoft.com/en-us/powershell/module/azureinformationprotection/protect-rmsfile?view=azureipps

相关问题