2017-04-17 45 views
2

我有一个打开的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 existsHow 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

+0

也许你只是没有安全权限。你能手动打开文件并保存吗? –

回答

4

根据the documentation for the Open() method,第三个参数允许您指定是否以只读模式打开文件。

它设置为$false

​​
+0

谢谢你的回答,但它仍然不起作用。它起初工作,但当我替换文件时,它再次给了我相同的只读错误。在完成测试后,我想用原始模板进行测试,以便用原始模板替换文件并运行SSIS包。当我打开文件时,没有密码。所以我运行代码frm PoSh并出现相同的只读错误。我想要一个代码保存一个只读文件。看起来像其他一切只是打开文件,因为不是只读的,但保存相同的名称是一个问题。用不同的名字作品保存。 – Stephanie

+0

这看起来像是一个覆盖问题。在应用密码后无法覆盖 – Stephanie

+0

您是否考虑过使用密码保存到临时文件/其他文件名,然后删除原始文件并重命名临时文件? –

相关问题