【发布时间】:2017-09-13 14:54:48
【问题描述】:
我有一个要打开的 Excel 文件,对其应用密码,然后使用 PowerShell 保存它。我收到以下错误:
使用“3”参数调用“SaveAs”的异常:“无法保存为该名称。文档以只读方式打开。” 在 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
【问题讨论】:
-
也许您只是没有安全权限。可以手动打开文件保存吗?
标签: excel powershell readonly