Powershell just deleting excel through task scheduler

Christopher Jack 101 Reputation points
2022-07-07T08:33:49.617+00:00

Hi,

I have the following scrip with is called from Windows Task Scheduler

$file = 'C:\Excel\Sage.xlsx'  
$x1 = New-Object -ComObject "Excel.Application"  
$x1.Visible = $false  
$enddate = (Get-Date).tostring("dd-MM-yy")  
$filename = 'C:\Excel\Test.xlsx'  
$wb = $x1.workbooks.Open($file)  
$wb.refreshall()  
$wb.SaveAs($filename)  
$wb.Close()  
$x1.Quit()  
Remove-Variable wb,x1  
Remove-Item $file  
Rename-Item $filename -NewName "Sage.xlsx"  

It runs fine an executes in Powershell editor and in vs code - however when i run it calling Powershell from the windows task scheduler ..all it does is delete the file called Sage..

Any idea why it is not doing any of the other instructions?

Office Development
Office Development
Office: A suite of Microsoft productivity software that supports common business tasks, including word processing, email, presentations, and data management and analysis.Development: The process of researching, productizing, and refining new or existing technologies.
3,311 questions
Excel Management
Excel Management
Excel: A family of Microsoft spreadsheet software with tools for analyzing, charting, and communicating data.Management: The act or process of organizing, handling, directing or controlling something.
1,618 questions
Windows Server PowerShell
Windows Server PowerShell
Windows Server: A family of Microsoft server operating systems that support enterprise-level management, data storage, applications, and communications.PowerShell: A family of Microsoft task automation and configuration management frameworks consisting of a command-line shell and associated scripting language.
5,283 questions
0 comments No comments
{count} votes

Accepted answer
  1. Rich Matheisen 44,081 Reputation points
    2022-07-07T15:03:05.477+00:00

    You really should read the information in the link posted by @Viorel .

    Since you're not doing any error checking in your code I don't think you'll have much success in discovering the problem. The most likely cause is that the New-Object is failing and the variable "$x1" contains a $null value.

    If you're going to write code that runs on a Windows server and works with Excel files then you should be using the ImportExcel PowerShell module: 7.0.1. The module does not use MS Office objects and works only with the software delivered with MS Windows (both client and server).

    1 person found this answer helpful.

1 additional answer

Sort by: Most helpful
  1. Viorel 110.1K Reputation points
    2022-07-07T09:11:18.34+00:00

    Probably Excel cannot be used from services and Task Scheduler: https://support.microsoft.com/en-us/topic/considerations-for-server-side-automation-of-office-48bcfe93-8a89-47f1-0bce-017433ad79e2. Maybe you must specify a normal user account in Task Scheduler?

    2 people found this answer helpful.