When I run the PowerSheel script manually – through a .bat file that executes it with the PowerShell interpreter – it correctly executes an SQL query and creates an Excel file and e-mails it.
If I automate it – run the .bat file that runs the PowerShell file with the interpreter through the Windows job scheduler every night – then the e-mail is sent without the file.
It is difficulty to copy the code here because I made a nice framework many functions deep with lambda-functions and all, but generally:
$ExcelWorkBook.SaveAs($Filename)
$ExcelWorkBook.Close()
$ExcelApp.Quit()
(…)
Sleep -Seconds 500
(…)
$MailMessage.Attachments.Add($Filename)
$SMTP.Send($MailMessage)
I have heard that Excel does not actually support GUI-less automation (windows task scheduler) but that actually worked for me through a different framework.
What can I do to make it work, if cannot how can I generate Excel files from PowerShell in a different way, or how can I just easily generate and e-mail reports in PowerShell?
if you are running windows 2008 or above, then the job is probably executed in session0 (read about session0 isolation at microsoft).
You have to create Desktop-Folders for session0, read more here:
http://social.msdn.microsoft.com/Forums/en/innovateonoffice/thread/b81a3c4e-62db-488b-af06-44421818ef91
Windows 2008 Server x64
Please make this folder
C:\Windows\SysWOW64\config\systemprofile\Desktop
Windows 2008 Server x86
Please make this folder
C:\Windows\System32\config\systemprofile\Desktop
Then restart machine and try again.
I got it working with GUI-less Excel automation via task scheduler and powershell, done by creating those folders.