Stephanie
Stephanie

Reputation: 516

How to save a read-only file using PowerShell

I have an Excel file that I am opening, applying a password to it, and then saving it using PowerShell. I am getting the following error:

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

I have searched a lot but nothing has resolved my issue. Here are some questions I refered to already: Powershell - SaveAs function when file already exists and How to Remove ReadOnly Attribute on File Using PowerShell?.

My code:

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)

I have tried these codes after the Workbooks.Open statement to see if it will save the read-only file, and it worked, but then when I closed and reopened the code it stopped working:

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

Code2:
Set-ItemProperty "$($FilePath)" -name IsReadOnly -value $false

Actually, the file is not read only but the folder is and I am unable to check out the box that says read only. Same as this problem: 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

Upvotes: 2

Views: 2653

Answers (1)

Mathias R. Jessen
Mathias R. Jessen

Reputation: 174730

According to the documentation for the Open() method, the third argument allows you to specify whether to open the file in read-only mode.

Set it to $false:

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

Upvotes: 4

Related Questions