Home > other >  Powershell , Cannot save as that name. Document was opened as read-only
Powershell , Cannot save as that name. Document was opened as read-only

Time:02-27

How to avoid remove read-only , I need to normal excel without read-only. I have below code:

$excelfile="C:\Users\Administrator\Pictures\unprotect_org - Copy\unprotect - Copy (2).xlsx"
$excel = New-Object -ComObject Excel.Application
$excel.Visible = $false
$excel.DisplayAlerts = $false
$wb = $excel.Workbooks.Open($excelfile,$true,123)
$wb.SaveAs($excelfile,[Type]::Missing,$password)
$excel.Quit()

I got below error:

Cannot save as that name. Document was opened as read-only.
At line:1 char:1
  $wb.SaveAs($excelfile,[Type]::Missing,$password)
  ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
      CategoryInfo          : OperationStopped: (:) [], COMException
      FullyQualifiedErrorId : System.Runtime.InteropServices.COMException

enter image description here

2nd things , why microsoft execel open in task manager, How can I close this exe. enter image description here

Please help me to resolve this error.

CodePudding user response:

Two things you'll want to change - opening in read-write mode, and ensuring Quit() is called regardless of terminating errors.

To avoid opening the workbook in read-only mode, change the value of the 3rd parameter argument passed to Open():

$wb = $excel.Workbooks.Open($excelfile,$true,$false)
#                                              ^ 
#                                     This is the ReadOnly parameter

To ensure Quit() is always called, use a try/finally statement:

$excelfile="C:\Users\Administrator\Pictures\unprotect_org - Copy\unprotect - Copy (2).xlsx"
$excel = New-Object -ComObject Excel.Application
try {
  $excel.Visible = $false
  $excel.DisplayAlerts = $false
  $wb = $excel.Workbooks.Open($excelfile,$true,123)
  $wb.SaveAs($excelfile,[Type]::Missing,$password)
}
finally {
  $excel.Quit()
}

If PowerShell reaches the first statement inside the try block, it guarantees that the finally block will execute before returning control from the block - even if the call to SaveAs() (or any other invocation) throws a terminating exception

  • Related