我有一个打开的Excel文件,将密码应用于该文件,然后使用PowerShell保存。我收到以下错误:如何使用PowerShell保存只读文件
Exception calling "SaveAs" with "3" argument(s): "Cannot save as that name. Document was opened as read-only." At C:\PasswordProtectExcelFiles.ps1:38 char:45
+ $a = $wb.SaveAs("$($FilePath)",$xlNormal,"$($Password)")
+ ~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : ComMethodTargetInvocation
我已经搜索了很多,但没有解决我的问题。以下是我提到的一些问题: Powershell - SaveAs function when file already exists和 How to Remove ReadOnly Attribute on File Using PowerShell?。
我的代码:
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语句之后尝试了这些代码,看看它是否会保存只读文件,和它的工作,但后来当我关闭并重新打开代码它停止工作:
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-server-2008
也许你只是没有安全权限。你能手动打开文件并保存吗? –