如何使用PowerShell保存只读文件

我有一个打开的Excel文件,对其应用密码,然后使用PowerShell进行保存。 我收到以下错误:

使用“3”参数调用“SaveAs”的exception:“不能保存为该名称,文档以只读方式打开”。 在C:\ PasswordProtectExcelFiles.ps1:38 char:45
+ $ a = $ wb.SaveAs(“$($ FilePath)”,$ xlNormal,“$($ Password)”)
+ ~~~~~~~~~
+ CategoryInfo:NotSpecified:(:) [],MethodInvocationException
+ FullyQualifiedErrorId:ComMethodTargetInvocation

我搜查了很多,但没有任何解决我的问题。 以下是我已经提到的一些问题: 当文件已经存在时Powershell – SaveAs函数以及如何使用PowerShell删除文件上的ReadOnly属性?

我的代码:

param([string]$FilePath, [string]$Password ) $xl = new-object -comobject excel.application $xl.Visible = $True $xl.DisplayAlerts = $False $wb = $xl.Workbooks.Open("$($FilePath)") $a = $wb.SaveAs("$($FilePath)",$xlNormal,"$($Password)") $a = $xl.Quit() $a = Release-Ref($wb) $a = Release-Ref($xl) 

我已经在Workbooks.Open语句之后尝试了这些代码,看看它是否会保存只读文件,它工作,但是当我closures并重新打开代码时,它停止工作:

 Code1: $file = Get-Item "$($FilePath)" if ($file.IsReadOnly -eq $true) { $file.IsReadOnly = $false } Code2: Set-ItemProperty "$($FilePath)" -name IsReadOnly -value $false 

实际上,该文件不是只读的,但该文件夹是,我无法签出说只读的框。 与此问题相同: https : //social.technet.microsoft.com/Forums/windowsserver/en-US/f7ec4fc5-3bbe-4fd0-a8ca-c4ead75b010c/unable-to-removeclear-readonly-attribute-from-folder-in -Windows服务器-2008

根据Open()方法的文档 ,第三个参数允许您指定是否以只读模式打开文件。

将其设置为$false

 $wb = $xl.Workbooks.Open("$($FilePath)", 0, $false)