Error when trying to protect Excel file with PowerShell - excel

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)

Related

Change Worksheet Name (Excel) via Powershell

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()

Powershell excel(xlsx) how unprotect excel sheet and excel workbooks with know password

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()

[powershell]Pasting table from Excel to Word, autofit table

Currently working on a robot where I want to download an excel file from a system, copy paste the contents of the excel file to a word file as an embedded excel table, but the table is wider than the page (it is already in landscape mode). I am using a powershell script in DAS to execute this step. To solve the problem normally, I would simply right-click on the table and use Autofit -> Fit to Window. How do I do this in powershell?
My script is currently like this:
$word = new-object -comobject Word.application
$word.visible = $true
$doc1 = $word.documents.open($destination)
$bookmark1 = $doc1.Bookmarks.Item("FacilitySheet")
$xl = New-Object -comobject Excel.Application
$xl.Visible = $true
$xl.DisplayAlerts = $False
$wb = $xl.Workbooks.Open("C:\Users\Pater\Downloads\spreadsheet.xlsx")
$ws = $wb.ActiveSheet
$Range1 = $ws.UsedRange.Cells
$RowCount = $Range1.rows.count
$CopyRange = $ws.Range("A1:O$RowCount").Copy()
$bookmark1.Range.Paste()
To solve this you must set the AutoFitBehavior to the desired value. Please check https://learn.microsoft.com/en-us/office/vba/api/word.table.autofitbehavior for the allowed values and take into account that the values wdAutoFitContent, etc may not be accessed from Powershell, so you must set the raw values (1 for wdAutoFitContent, for example)
$word = new-object -comobject Word.application
$word.visible = $true
$doc1 = $word.documents.open($destination)
$bookmark1 = $doc1.Bookmarks.Item("FacilitySheet")
$xl = New-Object -comobject Excel.Application
$xl.Visible = $true
$xl.DisplayAlerts = $False
$wb = $xl.Workbooks.Open("C:\Users\Pater\Downloads\spreadsheet.xlsx")
$ws = $wb.ActiveSheet
$Range1 = $ws.UsedRange.Cells
$RowCount = $Range1.rows.count
$CopyRange = $ws.Range("A1:O$RowCount").Copy()
$bookmark1.Range.Paste()
$bookmark1.Range.AutoFitBehavior(1)

Formatting excel file using Powershell

I am currently trying to take a csv file generated from a VBScript, and use powershell to convert it to an xls then save it. (Using it as an offline Database file) Problem, is that one column (Column E) is for SKU's and has leading 0's that get lost during the translation. I am getting errors when trying the following. Powershell is new to me, so I could be making a simple mistake:
$xl = new-object -comobject excel.application
$xl.visible = $true
$Workbook = $xl.workbooks.open("file location.csv")
$Worksheets = $Workbooks.worksheets
$Worksheets.Columns.("E").NumberFormat = "00000000000"
$Workbook.SaveAs("file location.xls",1)
$Workbook.Saved = $True
$xl.Quit()
EDIT: I got it to work! Here's the following, if anyone has any pointers:
$excel = new-object -comobject excel.application
$excel.visible = $true
$Workbook = $excel.workbooks.open("file location.csv")
$Worksheets = $Workbooks.worksheets
$Worksheet = $Workbook.Worksheets.Item(1)
$Range = $Excel.Range("E:E").EntireColumn
$Range.NumberFormat = "00000000000"
$Workbook.SaveAs("file location.xls",1)
$Workbook.Saved = $True
$excel.Quit()
You can achieve the same thing with changing
$Worksheets.Columns.("E").NumberFormat = "00000000000"F15
to
$workbook.ActiveSheet.Columns.Item("E").NumberFormat = "00000000000"
from the first example to have less code.

Excel functions in powershell

I am new to Powershell and I need to parse text file into excel and edit content.
I managed to open file with the following script:
$Excel = New-Object -ComObject Excel.Application
$Excel.Visible = $true
$Excel.DisplayAlerts = $false
$Excel.Workbooks.OpenText( "Documents\myfile.txt")
It runs without exception, but the data I'm left with tells me the file is not loaded properly.
I need to set parameters like FieldInfo for export.
How do I do this?
Thanks for help.
You have to get the item from the file in order to load it in excel.
DO like this:
$excel = new-object -comobject excel.application
$file = get-item "E:\myfile.txt" # Mention the path of the file
$excel.Visible=$true
$excel.displayalerts = $False
$wb = $excel.workbooks.open($file)
Hope it helps you.
When you bring data into Excel via text file or manual input, Excel will try to interpret what type of data it is, text, date or number. You are bringing in text that looks like a number to Excel.
One solution is to make Powershell do all the work, get it to load the file and then loop through each row. You can then force the format before loading the data.
Something like this:
$Excel = New-Object -ComObject Excel.Application
$Excel.Visible = $true
$wb = $Excel.Workbooks.add()
$ws = $wb.Worksheets[1]
Import-Csv "Documents\myfile.txt" | % {$i = 1}{
$ws.Range("A" + $i).NumberFormat = '#'
$ws.Range("A" + $i).Value = $_.Field1
#Repeat for each field
$i++
)

Resources