Powershell export-excel working with sheets - excel

I'm trying to autofit columns in sheet1 using following code.
$Userlijst | Export-Excel $ExportUsersXLS -autofilter #-WorksheetName "Sheet1"
$excel = $exportusersxls
write-host "xlsx : " $excel
$sheet = $excel.Workbook.Worksheets['Sheet1']
write-host "Sheetname : " $sheet
foreach ($c in 1..9) {Set-ExcelRange -Address $sheet.Column($c) -AutoFit }
Export-Excel -ExcelPackage $excel
The output errors :
xlsx : c:\scripts\DepartmentUsers.xlsx
Cannot index into a null array.
At C:\scripts\Get-Departments-Users.ps1:46 char:1
$sheet = $excel.Workbook.Worksheets['Sheet1']
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : NullArray
Sheetname :
You cannot call a method on a null-valued expression.
At C:\scripts\Get-Departments-Users.ps1:48 char:23
... h ($c in 1..9) {Set-ExcelRange -Address $sheet.Column($c) -AutoFit }
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
CategoryInfo : InvalidOperation: (:) [], RuntimeException
FullyQualifiedErrorId : InvokeMethodOnNull

Related

what positional parameter should I be looking for when trying to delete java version 1.8.0_321

PS C:\Users\family> remove-item C:\Users\family> java -version "1.8.0_321"
Remove-Item : A positional parameter cannot be found that accepts argument 'java'.
At line:1 char:1
+ remove-item C:\Users\family> java -version "1.8.0_321"
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [Remove-Item], ParameterBindingException
+ FullyQualifiedErrorId : PositionalParameterNotFound,Microsoft.PowerShell.Commands.RemoveItemCommand

Powershell script works in ISE / Console but not Task Scheduler

I currently have a script that allows me to convert any excel spreadsheets within a specific folder to PDF documents which are saved in another folder. The script works great if you run it from Powershell ISE / Console. However, if you run the script by creating a task within Windows Task Scheduler it fails.
ZAOCC.ps1
Start-Transcript -Path 'C:\Temp\Log.txt'
Install-Module -Name ImportExcel -Force
$path = 'C:\Temp\Excel'
$path2 = 'C:\Temp\PDF'
$xlFixedFormat = 'Microsoft.Office.Interop.Excel.xlFixedFormatType' -as [type]
$excelFiles = Get-ChildItem -Path $path -include *.xls, *.xlsx -recurse
$objExcel = New-Object -ComObject excel.application
$objExcel.visible = $false
$date = Get-Date -Format 'dd.MM.yyyy'
foreach($wb in $excelFiles)
{
$filepath = Join-Path -Path $path2 -ChildPath ('Mine Control Record - ' + $date + '.pdf')
$workbook = $objExcel.workbooks.open($wb.fullname, 3)
$workbook.Saved = $true
"Saving $filepath"
$workbook.ExportAsFixedFormat($xlFixedFormat::xlTypePDF, $filepath)
$objExcel.Workbooks.close()
}
$objExcel.Quit()
I have included Start-Transcript and found the following errors when running the script through task scheduler:
Microsoft Excel cannot access the file 'C:\Temp\Excel\Test.xlsx'. There are several possible reasons:
• The file name or path does not exist.
• The file is being used by another program.
• The workbook you are trying to save has the same name as a currently open workbook.
At C:\Temp\ZAOCC.ps1:16 char:5
+ $workbook = $objExcel.workbooks.open($wb.fullname, 3)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : OperationStopped: (:) [], COMException
+ FullyQualifiedErrorId : System.Runtime.InteropServices.COMException
Microsoft Excel cannot access the file 'C:\Temp\Excel\Test.xlsx'. There are several possible
reasons:
• The file name or path does not exist.
• The file is being used by another program.
• The workbook you are trying to save has the same name as a currently open workbook.
At C:\Temp\ZAOCC.ps1:16 char:5
+ $workbook = $objExcel.workbooks.open($wb.fullname, 3)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : OperationStopped: (:) [], COMException
+ FullyQualifiedErrorId : System.Runtime.InteropServices.COMException
The property 'Saved' cannot be found on this object. Verify that the property exists and can be set.
At C:\Temp\ZAOCC.ps1:17 char:5
+ $workbook.Saved = $true
+ ~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : PropertyNotFound
The property 'Saved' cannot be found on this object. Verify that the property exists and can be
set.
At C:\Temp\ZAOCC.ps1:17 char:5
+ $workbook.Saved = $true
+ ~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : PropertyNotFound
Saving C:\Temp\PDF\Mine Control Record - 10.07.2020.pdf
You cannot call a method on a null-valued expression.
At C:\Temp\ZAOCC.ps1:19 char:5
+ $workbook.ExportAsFixedFormat($xlFixedFormat::xlTypePDF, $filepat ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
You cannot call a method on a null-valued expression.
At C:\Temp\ZAOCC.ps1:19 char:5
+ $workbook.ExportAsFixedFormat($xlFixedFormat::xlTypePDF, $filepat ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
PS>$global:?
True
My task within Task Scheduler is set to run with admin privileges with the following settings:
Program/Script powershell.exe
Add arguments(optional) -ExecutionPolicy Bypass C:\Temp\ZAOCC.ps1
Any help would be appreciated!
Solution turned out to be an excel bug. Followed the solution here: Powershell script cannot access a file when run as a Scheduled Task

Powershell script won't run as system when logged out, but works fine as user logged on

I have a PowerShell script to convert a .xls file to .txt file. It runs fine in PowerShell and as a scheduled task when "run only when the user logged on" is checked as my user account, but if I try the system and run whether logged on or not, it doesn't work.
I've tried different arguments and setting some security flags on the account already.
Some debugging shows this when running as system user:
Microsoft Excel cannot access the file 'C:\test\test.xls'. There are several possible reasons:
• The file name or path does not exist.
• The file is being used by another program.
• The workbook you are trying to save has the same name as a currently open workbook.
At C:\test\t.ps1:5 char:1
+ $WorkBook = $Excel.Workbooks.Open($file.Fullname)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : OperationStopped: (:) [], COMException
+ FullyQualifiedErrorId : System.Runtime.InteropServices.COMException
You cannot call a method on a null-valued expression. At
C:\test\t.ps1:6 char:1
+ $Workbook.SaveAs('c:\test\t.txt', 42) # xlUnicodeText
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
#excel processing
$Excel = New-Object -ComObject Excel.Application
$Excel.visible = $false
$Excel.DisplayAlerts = $false
$file = Get-ChildItem 'c:\test\test.xls'
$WorkBook = $Excel.Workbooks.Open($file.Fullname)
$Workbook.SaveAs('c:\test\t.txt', 42) # xlUnicodeText
# cleanup
$Excel.Quit()
[System.Runtime.Interopservices.Marshal]::ReleaseComObject($WorkBook) | Out-Null
[System.Runtime.Interopservices.Marshal]::ReleaseComObject($Excel) | Out-Null
[System.GC]::Collect()
[System.GC]::WaitForPendingFinalizers()
#powershell -ExecutionPolicy ByPass -File C:\test\t.ps1
The expected result creates a new txt file in the test folder, the actual result just produces nothing.

Type mismatch on excel data from powershell

Good day everyone.
I am a starting programmer in powershell and am trying to make a program input help desk calls into an excel sheet to import into the help desk ticketing system.
My script:
$excel_file_path = 'G:\IT\Helpdesk\Daily Calls.xlsx'
## Instantiate the COM object
$Excel = New-Object -ComObject Excel.Application
$ExcelWorkBook = $Excel.Workbooks.Open($excel_file_path)
$ExcelWorkSheet = $Excel.WorkSheets.item("sheet1")
$ExcelWorkSheet.activate()
## Find the first row where the first 7 columns are empty
$row = ($ExcelWorkSheet.UsedRange.Rows | ? { ($_.Value2 | ? {$_ -eq $null}).Count -eq 7 } | select -first 1)
$test = "this is a test"
$ExcelWorkSheet.Cells.Item($row,1) = $test
$ExcelWorkBook.Save()
$ExcelWorkBook.Close()
$Excel.Quit()
[System.Runtime.Interopservices.Marshal]::ReleaseComObject($Excel)
Now, I did take this from another page online and modified it to what I need, but it is giving me this error;
Type mismatch. (Exception from HRESULT: 0x80020005 (DISP_E_TYPEMISMATCH))
At H:\Scripts\Call_Log.ps1:12 char:1
+ $ExcelWorkSheet.Cells.Item($row,1)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : OperationStopped: (:) [], COMException
+ FullyQualifiedErrorId : System.Runtime.InteropServices.COMException
OR
Exception from HRESULT: 0x800A03EC
At H:\Scripts\Call_Log.ps1:11 char:1
+ $ExcelWorkSheet.Cells.Item($row,1) = $test
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : OperationStopped: (:) [], COMException
+ FullyQualifiedErrorId : System.Runtime.InteropServices.COMException
I don't understand what is going on or what is mismatched. Could anyone please help?

open a password protected Excel in powershell [duplicate]

This question already has answers here:
Script to open encrypted excel file, that has a dynamic filename ending in "mmddyyyy"
(2 answers)
Closed 5 years ago.
I'm trying to open a password protected excel sheet in powershell and output a report on how many rows are in the sheet.
the script works absolutely fine if the sheet isn't password protected but I can't seem to get powershell to open it if there is a password set.
my current script is
$Report = "S:\Business Support\excel tests\MI Tool - Live.csv"
$path = "S:\Business Support\excel tests"
[Array]$Results = $null
$excelSheets = Get-Childitem -Path $path -Include "MI Tool - Live.xlsm" -Recurse
$excel = New-Object -comobject Excel.Application
$excel.visible = $false
$password = "blablabla"
$updatelinks = 0
foreach($excelSheet in $excelSheets)
{
$workbook = $excel.Workbooks.Open($excelSheet,$updatelinks,$password)
$rowCount = $null
$worksheet = $workbook.sheets.item("Data")
$rowMax = ($worksheet.usedRange.rows).count
$rowCount += $rowMax
$Results += New-Object Psobject -Property #{
"File Name"=$excelSheet.Name
"Row Count"=$rowCount}
$excelSheet.Name
$workbook.Sheets.count
$rowCount
}
$excel.quit()
Stop-Process -Name EXCEL -Force
$Results | select "File Name","Row Count" | Export-Csv $Report -NoTypeInformation
This is the error I get:
Exception calling "Open" with "3" argument(s): "Open method of Workbooks class failed"
At line:3 char:35
+ $workbook = $excel.Workbooks.Open <<<< ($excelSheet,$updatelinks,$password)
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : ComMethodTargetInvocation
You cannot call a method on a null-valued expression.
At line:5 char:37
+ $worksheet = $workbook.sheets.item <<<< ("Data")
+ CategoryInfo : InvalidOperation: (item:String) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
If I take out the $password variable it works but I then have to enter the password manually.
Your Open overload is incorrect. The password is the 5th variable. Have a look at MSDN to see
expression .Open(FileName, UpdateLinks, ReadOnly, Format, Password, WriteResPassword, IgnoreReadOnlyRecommended, Origin, Delimiter, Editable, Notify, Converter, AddToMru, Local, CorruptLoad)
So you would need to populate ReadOnly and Format first I believe. You would have to populate those values.
$excel.Workbooks.open($path,0,0,5,$password)
Look at the MSDN to understand what the values represent in the 2,3 and 4 positions.

Resources