Excel macros run through powershell but not when run by windows task scheduler - excel

I have a script which checks a folder for excel files and then if this "threshold" is greater than 0 then a macro from another excel file is run that interact with these excel folders.
When I run the process manually through powershell ISE it works fine but when I use the windows task scheduler the powershell script runs but the excel macro called doesn't run. Any suggestions why this might be the case? This process used to run on a windows 2008 server fine but was migrated to windows server 2012 and won't run properly
if ($count -gt $threshold){
$excel = new-object -comobject excel.application
$workbook = $excel.workbooks.open("D:\TimesheetService\IS-FS - AutoTimesheetLoader v2.3 - UAT.xlsm")
$worksheet = $workbook.worksheets.item(1)
$excel.Run("ImportTime")
$workbook.close($false)
$excel.quit()
[System.Runtime.Interopservices.Marshal]::ReleaseComObject($excel)
Remove-Variable excel
}

You cannot use the COM Automation Excel library (new-object -comobject excel.application) from a scheduled task, unless that task is run in the window station (session) of the currently logged-on user.
That is, in order to use the COM Excel library from a scheduled task, you must have the Run only when user is logged on option chosen for it, which you may not want, for two reasons:
It restricts your task to run only when someone happens to be logged on.
The currently logged-on user will see the task's window as it runs - unless you take extra steps to hide it (which can't be done with powershell.exe itself).
Note: There is a workaround that is currently effective, but it is unsupported, which is why it is better to avoid it - see this answer to a related superuser.com question.
Therefore, consider alternatives that do not have this restriction, such as the DocumentFormat.OpenXml Nuget package.
See this Microsoft support article for background information.

I was trying to do the same thing. This got it working for me https://www.jonashendrickx.com/2016/04/07/when-run-as-scheduled-task-excel-wont-save-with-powershell/
The last two steps is what I needed. Check to make sure these folders exist
On a 32-bit and 64-bit operating system:
C:\Windows\System32\config\systemprofile\Desktop
On a 64-bit operating system:
C:\Windows\SysWOW64\config\systemprofile\Desktop

Related

Weird behavior when launching powershell through different ways

I have a Powershell script assigned to the context menu and it has been running fine. Recently, after I've reset my win10 system and then manually reconfigured my whole system Powershell begins to behave weirdly. The script won't be run correctly anymore, after a lot of researches I find that the problem is caused by the Set-Clipboard cmdlet which being the PCSX version when launching through the context menu where it being the original version if I launch powershell manually. How comes it happen? My script has Set-Clipboard with -value parameter which is not present in PCSX version and it causes an error.

Scheduled task not run using x86 version of Powershell

I have written a Powershell script and it is saved in a .ps1 file. It only works with the 32-bit version of the Powershell that is located in
%SystemRoot%\syswow64\WindowsPowerShell\v1.0\powershell.exe
The script works when I run it manually but it is not run via Windows Task Scheduler. I am running the task as the same user that runs the script. In the Action part of my task I put the above address as Program/script and I write the full path of my .ps1 file as Add Arguments (optional). But it does not seem to work. I have also tried with putting the parent folder of my .ps1 file as Start in value to no avail.
How can I tell Task Scheduler to run my Powershell script using the 32-bit version?
UPDATE: I have to add here that my script actually opens an Excel file, refreshes it and then closes it. I know that using Excel in a non-interactive environment is a bad idea. But I still don't know if this is the reason my script is not run.
Highly suspect Excel is the reason this appears not to work. Have your script do something non-Excel (e.g. create file) and check if this part was executed fine
Two major gotchas I've come across when automating Excel:
Create empty folders if they don't exist (excel automation bug)
Ensure DCOM security settings are configured to allow Excel to run. This is still required if you are running task as same user who manually runs script.
When DCOM permissions are not set correctly and running the script as an automated task, you will get the below error. Saw this as session was transcribed, and transcription output to text file.
New-Object : Retrieving the COM class factory for component with CLSID
{00024500-0000-0000-C000-000000000046} failed due to the following
error: 80070005 Access is denied. (Exception from HRESULT: 0x80070005
(E_ACCESSDENIED)).
You could adopt your script to determine the current powershell version and invoke the same script with the 32bit version if necessary. Put these lines on the top of your script:
# ensure the script is running with the 32bit powershell
if ($env:Processor_Architecture -ne "x86")
{
$psx86 = Join-Path $env:SystemRoot '\syswow64\WindowsPowerShell\v1.0\powershell.exe'
& $psx86 -noprofile -file $myinvocation.Mycommand.path -executionpolicy bypass
exit
}
Note: You can append parameter to the powershell invoke in case your script requires them.

Using powershell to convert csv file to excel

I'm running a PowerShell script that converts a CSV file to Excel. When I run it manually it works fine, but when I run it through a scheduled task it fails. Here is the error I'm getting:
Exception calling "Open" with "1" argument(s): "Open method of Workbooks class
failed"
At C:\PowerShell\Weekly\WeeklyReport.ps1:337 char:34
+ $workbook = $excel.Workbooks.Open <<<< ($csvFilePath)
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : ComMethodTargetInvocation
I'm using the same account in the scheduled task as I am when logged in. I also had the scheduled task use the local administrator account, but still had the same issue. What I'm actually launching is a VB script, which in turn launches a .bat file, which lists out a few PowerShell scripts. The VB script is used to hide the window so it doesn't show up when it's running. If I manually run the VB script it runs fine, but when running it through scheduled task it fails with the error I listed. I'm using Windows Server 2008 and I have Office 2003 installed. Here is the portion of the PowerShell script that is failing:
$excel = New-Object -ComObject excel.application
$excel.visible = $False
$excel.displayalerts=$False
$workbook = $excel.Workbooks.Open($csvFilePath)
$workSheet = $workbook.worksheets.Item(1)
It's failing on the line
$workbook = $excel.Workbooks.Open($csvFilePath)
Any help would be greatly appreciated. Thank you!
Okay so I found my problem. I went into dcomcnfg. Since my application "Excel" was 32bit and I was running on a 64bit machine I had to lunch the 32 bit version of it:
c:\Windows\SysWOW64>mmc comexp.msc /32
Once I was in there I went into Component Services -> Computers -> My Computer -> DCOM Config. In that list I fond Microsoft Excel Application and went into properties. In the security tab I hit the radio box for "Customize" next to each one and hit the edit button for each one and added the user account I was lunching the scheduled task with. Full access to everything. Under "Identity" tab I hit the radio circle for "This user" and again put the information for the user I was running the task with. I probably didn't need to do all of that, I'm sure it only took one thing to fix the problem, but I wasn't sure which one to do so I did them all. And it worked.

powershell IQY dump script fails

I'm currently working on automating a powershell script to make a dump of a small DB.
The database is accessible through a company Sharepoint and I am leveraging an IQY file exported from said Sharepoint to read the database contents.
When I run the script manually (i.e. calling it from the command line), it works with no issues, but when I try and start the script from Task Scheduler, the following exception is raised:
System.Reflection.TargetInvocationException
the line that is generating the exception is:
$iqy = $xl.Workbooks.Open($query, 2, $true)
Where $xl is a new Excel.Application ComObject, created correctly and $query is a string containing the full file path of the iqy file.
As for my configuration, I'm trying to run my script on a Windows Server 2008R2, using a local administrator user (same user that is supposed to launch the scheduled script), which is also authorized to access the Sharepoint. I'm running Powershell 3.0. I'm not loading any Sharepoint-related snapins.
The only answers I found poking around hinted at granting "Trust" to the IQY file location and the Sharepoint itself in Excel. That did not help.
The Exception also seems to point at a sharepoint issue, but since the script runs fine when started manually, I cannot understand how it could be anything to do with Sharepoint.
Am I missing some intricacy of the Task Scheduler?
Any help would be greatly appreciated.
Never mind, I seem to have found an answer.
If anyone is encountering the same issue, it appear the Excel Com Object has a bug that does not allow it to run from the Task Scheduler if you set it to run regardless of whether the user is logged in.
To circumvent that create the following 2 folders on the machine where the script is supposed to run:
(32Bit, always)
C:\Windows\System32\config\systemprofile\Dektop
(64Bit)
C:\Windows\SysWOW64\config\systemprofile\Desktop
After creating the folders, it worked as expected.
Source: http://social.technet.microsoft.com/Forums/windowsserver/en-US/aede572b-4c1f-4729-bc9d-899fed5fad02/run-powershell-script-as-scheduled-task-that-uses-excel-com-object?forum=winserverpowershell

Powershell Excel Automation - Save/Open fails in Scheduled Task

I created a simple powershell script that will create an excel instance and save a workbook:
$excel = New-Object -ComObject Excel.Application
$workbook = $excel.Workbooks.Open("C:\Test\foo.xls")
$workbook.SaveAs("C:\Test\bar.xls")
# cleanup code ...
When I run this from powershell directly it works fine.
I created a scheduled task that runs it, and when I have the option set that will "Run only when the user is logged in" then it will run fine.
When I change this option to run whether the user is logged in or not, it will fail trying to open/save the file. The account I am using has the correct permissions. I have the account set up to Log in as a service.
Any suggestions?
I've been burned by this and didn't want to rewrite the code. I saw your post and several others which made me about to give up. However, my persistence paid off. I was trying to have Jenkins run a script to inventory our production environment and output to Excel. I didnt want a text doc because I was highlighting software versions that didnt match in RED, so needed Excel.
Here is the answer that worked for me:
You have to create a folder (or two on a 64bit-windows):
(32Bit, always)
C:\Windows\System32\config\systemprofile\Desktop
(64Bit)
C:\Windows\SysWOW64\config\systemprofile\Desktop
Link that someone provided as the source:
http://www.patton-tech.com/2012/05/printing-from-scheduled-task-as.html
My source was:
http://social.technet.microsoft.com/Forums/en/winserverpowershell/thread/aede572b-4c1f-4729-bc9d-899fed5fad02
I remember having to do something similar in a C# application, which went well when you build it on Visual Studio, but running under a service on the CI server failed. This I believe is the limitation of Office Automation itself and Microsoft doesn't recommend / support doing this at all Look at Considerations for server-side Automation of Office here - http://support.microsoft.com/kb/257757. It shows the problems and the alternatives.
In my case, I had to give up Office Interop, and use EPPlus ( http://epplus.codeplex.com/ ) to work with excel. It worked great and was much faster as well.

Resources