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
2nd things , why microsoft execel open in task manager, How can I close this exe.
Please help me to resolve this error.
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
I have an challenge that I need to change on a daily basis in a XLSX document the existing sheet name to a new sheet name and than save it
My script looks like this:
$xlspath = "C:\Users\roger\Test - Test\Daily_Files\Testfile.xlsx"
$xldoc = new-object -comobject Excel.application
$xldoc.DisplayAlerts = $false
$xldoc.Visible =$false
$workbook = $xldoc.Workbooks.Open($xlspath)
$worksheet = $workbook.worksheets.item(1)
$worksheet.name = "Headcount"
$workbook.Save = ($xlspath)
$workbook.Close()
$xldoc.Quit()
I always get this error - even so the file gets save and the name has changed:
C:\CommonUserData\Roger\Test\Test.ps1:8 char:1
+ $workbook.Save = "C:\Users\roger\Test - Test\Daily_Files\ ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : OperationStopped: (:) [], COMException
+ FullyQualifiedErrorId : System.Runtime.InteropServices.COMException ```
Does someone have an idea how to solve this or make this a very simple script?
You don't even need the .Save() or .SaveAs() methods for this. Just close the workbook with parameter $true:
$xlspath = "C:\Users\roger\Test - Test\Daily_Files\Testfile.xlsx"
$xldoc = New-Object -ComObject Excel.application
$xldoc.DisplayAlerts = $false
$xldoc.Visible =$false
$workbook = $xldoc.Workbooks.Open($xlspath)
$worksheet = $workbook.worksheets.item(1)
$worksheet.Name = "Headcount"
$workbook.Close($true) # save the updated workbook
$xldoc.Quit()
# Important: remove references to the used COM objects when finished so they don't keep lingering in memory
$null = [System.Runtime.Interopservices.Marshal]::ReleaseComObject($worksheet)
$null = [System.Runtime.Interopservices.Marshal]::ReleaseComObject($workbook)
$null = [System.Runtime.Interopservices.Marshal]::ReleaseComObject($xldoc)
[System.GC]::Collect()
[System.GC]::WaitForPendingFinalizers()
I have below code:
$excelfile="C:\Users\Administrator\Pictures\unprotect_org - Copy (2)\unprotect - Copy (2).xlsx"
$excel = New-Object -ComObject Excel.Application
$excel.Visible = $false
$excel.DisplayAlerts = $false
$wb = $excel.Workbooks.Open($excelfile,$false,123)
$wb.Unprotect(123);
$wb.Settings.Password = "";
$wb.Save($excelfile);
$excel.Quit()
I have problem with, PS script is opening ui excel application instead of remove password as without open excel.
Getting below error:
Unable to get the Open property of the Workbooks class
At line:1 char:1
+ $wb = $excel.Workbooks.Open($excelfile,$false,123)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : OperationStopped: (:) [], COMException
+ FullyQualifiedErrorId : System.Runtime.InteropServices.COMException
Please help to unprotect excel sheets and workbook using powershell.
Ok, here you go:
To open an Excel workbook with a password, you need to specify that password as the fith parameter on the Workbooks.Open() method:
$password = '123'
$excelfile = "C:\Users\Administrator\Pictures\unprotect_org - Copy (2)\unprotect - Copy (2).xlsx"
$excel = New-Object -ComObject Excel.Application
$excel.Visible = $false
$excel.DisplayAlerts = $false
$wb = $excel.Workbooks.Open($excelfile, $false, $false, [Type]::Missing, $password)
# remove the protection from this workbook
$wb.Unprotect($password)
# should not be needed, but does no harm
$wb.Password=$null
# close the workbook and save the changes
$wb.Close($true)
$excel.Quit()
# Important: remove the used COM objects from memory
$null = [System.Runtime.Interopservices.Marshal]::ReleaseComObject($wb)
$null = [System.Runtime.Interopservices.Marshal]::ReleaseComObject($excel)
[System.GC]::Collect()
[System.GC]::WaitForPendingFinalizers()
I'm trying to execute a PowerShell script for password protecting an Excel file.
this is the script:
Set objExcel = CreateObject(“Excel.Application”)
objExcel.Visible = True
objExcel.DisplayAlerts = FALSE
Set objWorkbook = objExcel.Workbooks.Add
Set objWorksheet = objWorkbook.Worksheets(1)
objWorksheet.Cells(1, 1).Value = Now
objWorkbook.SaveAs “C:\Test.xlsx”,,”%reTG54w”
objExcel.Quit
I tried running it using "run as PowerShell" but it closes automatically, I've also tried using the PowerShell ISE, the result is the one below:
the text for it is this:
At C:\Users\gasgu\OneDrive\Desktop\pwoershell.ps1:14 char:39
+ objWorkbook.SaveAs “C:\Test.xlsxâ€,,â€%reTG54wâ€
+ ~
Missing expression after ',' in pipeline element.
At C:\Users\gasgu\OneDrive\Desktop\pwoershell.ps1:14 char:39
+ objWorkbook.SaveAs “C:\Test.xlsxâ€,,â€%reTG54wâ€
+ ~
Missing argument in parameter list.
+ CategoryInfo : ParserError: (:) [], ParseException
+ FullyQualifiedErrorId : MissingExpression
I've found this script from this url: https://devblogs.microsoft.com/scripting/how-can-i-password-protect-an-excel-spreadsheet/
But if it worth mentioning, what I'm trying to do is to pick up an Excel file from my PC (.xlsx) and password protect it (creating a new copy) now, in this script what I don't understand is if it's picking the excel file from somewhere as I don't see a line that explicitly says this.
Edit: The script I was executing ended up not being PowerShell, per clarification of #BigBen (see comments and approved answer) the script is VBS. He provided with script in PowerShell that performs the needed result.
That is VBScript, not Powershell. Perhaps try this:
$excel = New-Object -ComObject Excel.Application
$excel.Visible = $true
$excel.DisplayAlerts = $false
$wb = $excel.Workbooks.Add()
$wb.Worksheets("Sheet1").Cells(1, 1).Value = Get-Date
$wb.SaveAs("C:\Test.xlsx",[Type]::Missing,"%reTG54w")
$excel.Quit()
Perhaps this:
$Files = Get-ChildItem C:\Users\xxxx\Downloads\test\*.xlsx -Recurse
$excel = New-Object -ComObject Excel.Application
$excel.Visible = $false
$excel.DisplayAlerts = $false
ForEach($File in $Files){
try {
$Workbook = $Excel.Workbooks.Open($File)
$Workbook.SaveAs($File,[Type]::Missing,"1234") #password set to 1234
$Workbook.Close($false)
$Excel.Quit()
}
catch {
}
}
[System.Runtime.Interopservices.Marshal]::ReleaseComObject($Excel)
The formula =LEFT(AB4,FIND(" ",AB5)-1 works perfectly in Excel, but seems to be causing errors in PowerShell where I get this error:
Exception from HRESULT: 0x800A03EC
At C:\Scripts\Excel_NUID2.ps1:21 char:1
+ $worksheet.range("AH5:AH$rows").formula = "=LEFT(AB4,FIND(" ",AB5)-1"
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : OperationStopped: (:) [], COMException
+ FullyQualifiedErrorId : System.Runtime.InteropServices.COMException
My PowerShell Script Code;
#Open Up the Workbook#
$excel = new-object -comobject Excel.Application
$excel.visible = $false
$workbook =
$excel.workbooks.open("c:\Users\Jack\documents\NUID_Status_Report.xlsx")
$worksheet = $workbook.Worksheets.Item(1)
$rows = $worksheet.range("A1").currentregion.rows.count
### Set up a filter ###
$headerRange = $worksheet.Range("a4","aj4")
$headerRange.AutoFilter() | Out-Null
#### Trims Password Expiration Date Name ###
$worksheet.range("AH4").formula = "Shortened Expiration Date"
[void]$worksheet.Cells.Item(1,1).select()
$excel.visible = $true
#### Trims Password Expiration Date Formula ###
$worksheet.range("AH5:AH$rows").formula = "=LEFT(AB4,FIND(" ",AB5)-1"
[void]$worksheet.Cells.Item(1,1).select()
$excel.visible = $true
Quotes within a quoted string need to be doubled-up.
$worksheet.range("AH5:AH$rows").formula = "=LEFT(AB4,FIND("" "",AB5)-1)"
'you can also get rid of the inside quotes with the CHAR function
$worksheet.range("AH5:AH$rows").formula = "=LEFT(AB4, FIND(CHAR(32), AB5)-1)"
ASCII character 32 is a space. I've also added a bracket to make a legal formula.
The purpose of the PowerShell script I am trying to write is - Open an excel document and run a macro. (The macro is stored in the Personal Workbook file - personal.xlsb and it runs successfully)
The problem -
When the excel file is opened via PowerShell code, it opens fine but when the macro is run by calling Run("NameOfMacro"), I get an error stating macro not found. I try to find the macro in the opened excel file and it does not appear in the macro list. This seems to be because the personal.xlsb file is not loading.
So I close the excel file, open it manually, but the macro is still missing. I then manually open the personal.xlsb file and notice that the macro exists however the macro still does not appear in the excel file or any other excel file I open thereafter.
After a frustrating hour trying to understand why is the personal.xlsb file stopped loading suddenly. I noticed another thing - if I kill the excel.exe process that was started by the PowerShell code (via task manager window) and then open any excel document the macro is available!!
So I have narrowed down the issue to this - The macros are not available because the Personal.xlsb is NOT opened/loaded WHEN I open excel file via PowerShell.
Does anyone have an idea why is this happening and what do I need to do to resolve this?
Code reference
$excel = New-Object -comobject Excel.Application
$FilePath = "D:\DailyReport.xls"
$workbook = $excel.Workbooks.Open($FilePath)
$excel.Visible = $true
$worksheet = $workbook.worksheets.item(1)
$excel.Run("SelectDataFromReport")
Error I get -
Exception calling "Run" with "31" argument(s): "Cannot run the macro 'SelectDataFromReport'. The macro may not be available in this workbook or all macro
s may be disabled."
At line:18 char:11
+ $excel.Run <<<< ("SelectDataFromReport")
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : DotNetMethodException
By the way, I use the 64 bit PowerShell console by default but I also tried running the code using 32 bit console but it didn't make a difference.
In excel I have added the location as a trusted location and i have allowed excel files to be opened by default in edit mode.
you can call the macro within the personal.xlsb like so:
$excel = New-Object -comobject Excel.Application
$wbPersonalXLSB = $excel.workbooks.open("$env:USERPROFILE\Application Data\Microsoft\Excel\XLSTART\PERSONAL.XLSB")
$FilePath = "D:\DailyReport.xls"
$workbook = $excel.Workbooks.Open($FilePath)
$excel.Visible = $true
$worksheet = $workbook.worksheets.item(1)
$excel.Run("PERSONAL.XLSB!SelectDataFromReport")
$wbPersonalXLSB.Close()
$workbook.save()
$workbook.close()
$excel.quit()
$x1 = New-Object -comobject Excel.Application
$wb = $x1.workbooks.open("$env:C:\teste\testamacro.xlsm")
$FilePath = "c:\teste\testamacro"
$workbook = $x1.Workbooks.Open($FilePath)
$x1.Visible = $true
$worksheet = $workbook.worksheets.item(1)
$x1.Run("testamacro.xlsm!SelectDataFromReport")
$wb.Close() $workbook.save()`
$workbook.close()
$x1.quit()