Run Powershell script as Scheduled task, that uses Excel COM object

Dear all.

I have created the script bellow to remove head on the excel file, is working when I run from powershel IDE but when I execute from schedule task is not working.

Can you please help me.

###########################  Script   ####################

$ErrorActionPreference = 'Stop'

$WbPath = 'C:\DWH\003_GA_BaseSalario_Orig'
$WbNewPath = 'C:\DWH\003_GA_BaseSalario.xlsx'

$WbPath2 = 'C:\DWH\006_OM_BasePoste_Orig.xlsx'
$WbNewPath2 = 'C:\DWH\006_OM_BasePoste.xlsx'


# Salario
#opening Excel and Workbook
$xl = New-Object -ComObject Excel.Application
$wb = $xl.Workbooks.Open($WbPath)
$ws = $wb.Worksheets.Item(1)

#Removing first two lines
$ws.Range("A1:A1").EntireRow.Delete()

#Save and Quit Excel
$wb.SaveAs($WbNewPath,[Microsoft.Office.Interop.Excel.XlFileFormat]::xlWorkbookDefault)
$wb.Close()
$xl.Quit()
[System.Runtime.InteropServices.Marshal]::ReleaseComObject($xl)

#Poste
#opening Excel and Workbook


$xl = New-Object -ComObject Excel.Application
$wb = $xl.Workbooks.Open($WbPath2)
$ws = $wb.Worksheets.Item(1)

#Removing first two lines
$ws.Range("A1:A1").EntireRow.Delete()

#Save and Quit Excel
$wb.SaveAs($WbNewPath2,[Microsoft.Office.Interop.Excel.XlFileFormat]::xlWorkbookDefault)
$wb.Close()
$xl.Quit()
[System.Runtime.InteropServices.Marshal]::ReleaseComObject($xl)

#####

  • PowerShell always runs in the context of the logged on user. Hence why this will work for you when you do this interactively. Running ST means you must provide a logged on identity. You are opening Excel, and Excel can only be open when a user is logged since it is directly related to the user profile that installed it. So, not really  PowerShell code issue or even ST standalone. It's how you are trying to use it.