Christian
Christian

Reputation: 29

PowerShell doesn't run as scheduled task when "Run whether user is logged on or not" is set

I have a PowerShell script that I want to schedule. Although it appears to run in Task Scheduler, it doesn't actually run my script. I have discovered that this is due to the fact that I have set the task to "Run whether user is logged on or not". If I turn this off, the task runs the script.

I found an article last week that suggested this was because I was using user-based variables but didn't suggest how I might get round it.

Can anyone help with my script below?

#UPDATE DATA IN EXCEL FILES
#THEN CREATE PDF FILE
[string]$path = "\\server\folder\"  #Path to Excel spreadsheets to save to PDF
[string]$savepath = "\\server\folder\Reports\"
[string]$dToday = Get-Date -Format "yyyyMMdd"

$xlFixedFormat = "Microsoft.Office.Interop.Excel.xlFixedFormatType" -as [type] 
$excelFiles = Get-ChildItem -Path $path -include *.xls, *.xlsx -recurse 

# Create the Excel application object
$objExcel = New-Object -ComObject excel.application 
$objExcel.visible = $false   #Do not open individual windows

foreach($wb in $excelFiles) 
{ 
# Path to new PDF with date 
 $filepath = Join-Path -Path $savepath -ChildPath ($wb.BaseName + "_" + $dtoday + ".pdf") 
 # Open workbook - 3 refreshes links
 $workbook = $objExcel.workbooks.open($wb.fullname, 3)
 $workbook.RefreshAll()

 # Give delay to save
 Start-Sleep -s 5

 # Save Workbook
 $workbook.Saved = $true 
"saving $filepath" 
 #Export as PDF
 $workbook.ExportAsFixedFormat($xlFixedFormat::xlTypePDF, $filepath) 
 $objExcel.Workbooks.close() 
} 
$objExcel.Quit()

Upvotes: 1

Views: 1782

Answers (1)

DarkLite1
DarkLite1

Reputation: 14695

I've had some problems while using the Microsoft.Office.Interop.Excel through a Scheduled Task too in the past. So we switched to using the following module:

This module makes use of the EPPLUS DLL which can easily be used from within a scheduled task as there is no need for an installed version of Microsoft Excel, which is in any case not a desirable solution on a server anyhow.

So i suggest you to have a look at this as it will surely help you.

If you still wish to use the Microsoft.Office.Interop.Excel object, you need to read this so you know that you need to manually create the following 2 folders:

C:\Windows\System32\config\systemprofile\Desktop  
C:\Windows\SysWOW64\config\systemprofile\Desktop

When these folders are available on your system, the Scheduled Task will most likely run correctly.

Upvotes: 4

Related Questions