PowerShell and Task Scheduler

On my Windows 2012 R2 server when I set the task to run my Powershell script with the "Run if user is logged in or not" and have the "Run with elevated permissions" the task does not run and get a (0x1) message. If I copy and paste the syntax into powershell it works fine.

Questions
1) Is see a number of post out there regarding the (0x1) exit code with Powershell and Task Scheduler. What is the trick to get this to work
2) My script geneates a CSV's file in a specific location. Will this be automatically over written daily?
3) What would be the easiest way to have all CSV files emailed to me? I believe powershell does have a send mail commandlet but have not used it before
LVL 21
compdigit44Asked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Chris MillardCommented:
What command are you putting into TaskScheduler? Are you using "PowerShell.exe" as the command, then having your script  (with full path) in the Arguments field?

If you CSV file name doesn't change, then yes it probably does get overwritten.
Qlemo"Batchelor", Developer and EE Topic AdvisorCommented:
You are asking 3 different questions, loosely connected, and do not even provide the necessary information.

If you do not show your script, how are we supposed to know whether it appends or overwrites CSV files, or what it does at all?

The question re: mailing attachments in PowerShell has been answered so often here. But in general it is
get-childitem C:\Temp\*.csv | Send-MailMessage -From me@domain.com -To you@domain.com -SmptServer mail.domain.com -Subject 'Test Results'

Open in new window


The base issue is that you (probably) need to run the script only when logged on if you need it running elevated. At least I would try that first.
compdigit44Author Commented:
Qlemo!!! Thank you for your help again.

1) For the powershell it is the one you helped me with and only pipping the results to |export-csv to I assume it will overwrite the existing file which is what I want.

2) So there is not way to run an elevated permission powershell script unless you are logged in???? This seem crazy?

BTW.. Thanks again for all of your great help I have learned so much :o)
OWASP: Forgery and Phishing

Learn the techniques to avoid forgery and phishing attacks and the types of attacks an application or network may face.

Qlemo"Batchelor", Developer and EE Topic AdvisorCommented:
1. Yes, Export-CSV without -Append (available with PS3 and above) will overwrite the file each time.
2. I have seen many issues with the "not logged in" state in Scheduled Tasks. If you want to run a script without being logged in, you usually have to set it up to run as administrative user - best with the integrated admin account, which does not need elevation (depending on the OS).
compdigit44Author Commented:
Thanks so what do you recommend I do to get this to work with Windows 2012 R2 and I already have tried to run the task under the local admin account with any luck
Qlemo"Batchelor", Developer and EE Topic AdvisorCommented:
With local admin and "only if logged in", too?
compdigit44Author Commented:
It works if I select "only if logged in" the point though is that I need these scripts to run automatically..
Qlemo"Batchelor", Developer and EE Topic AdvisorCommented:
Of course you want to run it automatically. Do you mean you don't want to have anyone logged in?
compdigit44Author Commented:
Sorry no my vague response....  I need the task to run automatically without anyone logged in..

I have been doing further research on this and added the -noninteractive -nologo switches into the argument box and will see how my task run tonight
compdigit44Author Commented:
Well my task to run the Powershell script to list the file sizes did not run as schedule and error out with the usually (0x1) yet my email script worked perfectly....
Qlemo"Batchelor", Developer and EE Topic AdvisorCommented:
Are this different scripts?
Can you show the generating code?
compdigit44Author Commented:
Yes they are different script....The one that worked is using the -noninteractive -nologo  switch just list the other script ..

The script that fails to run is running problem "Powershell" and have the arguments -noninteractive -nologo  and is running in elevelated mode as the local admin and run where the user is logged in or not..
Qlemo"Batchelor", Developer and EE Topic AdvisorCommented:
The "first" script is the email script? And you do not need to run that elevated, so it runs even if not logged in?

Again, we need something as script we can use for testing - the issue might be a generic or specific one, currently I cannot tell.
compdigit44Author Commented:
The script that is failing to run when no one is logged in is the file size script you wrote for me :o) I am running is under the context of the local administrator on the server but get the same result if I using my admin account as well.
Qlemo"Batchelor", Developer and EE Topic AdvisorCommented:
Sorry if I cannot remember having written that script, I did a lot of scripting the last two months :D.
You certainly are not referring to the script in http://www.experts-exchange.com/questions/28924358/Powershell-Script-List-Top-50-Largest-Files.html ?.
compdigit44Author Commented:
Yes that is the AWESOME script I am referring to...
Qlemo"Batchelor", Developer and EE Topic AdvisorCommented:
Great, because the script is written by oBdA, not me :p.
I suspect Write-Host being the culprit, but would have to write a test case for making sure. Meanwhile you can try by removing the line using that cmdlet for testing yourself.
compdigit44Author Commented:
Wait I just did another test to RUN my task manually without a schedule and get the same (0x1) error...
Qlemo"Batchelor", Developer and EE Topic AdvisorCommented:
Whether you define a trigger, or just kick-start the task manually, should not make any difference at all.
Did you try without the Write-Host line?
compdigit44Author Commented:
sorry for the delay in getting back to you...I have not tried the write-host line since I am not sure what to change since the script runs perfectly when I type everything in powershell as is..

In task schedule for what it is worth. For the program I list the full path for Powershell.exe and in the arguments box I have the following

-noninteractive -nologo c:\scripts\myscript.ps1 -path "W:\Drive Dept1" | export-csv c:\scripts\Output\Results.csv
compdigit44Author Commented:
Just as an update I am able to take this script and the arguments and paste it into Powershell directly and run it without issue. As soon I a try it in Task Scheduler I get the error (0x1). I have to  confirm again since it has been a long day but I believe I WAS able to run the script in task scheduler if the option to run only when logged in was selected.. and not logged in or logged off
Qlemo"Batchelor", Developer and EE Topic AdvisorCommented:
I've tested with the original script as provided by oBdA, and following command line as action:
powershell c:\temp\ee\get-bigfiles.ps1 -path C:\Temp\EE > C:\temp\ee\get-bigfiles.log

Open in new window

and it works with a Scheduled Task with elevated privs and "not logged in" setting. Even providing a non-existing path does not lead to 0x1. Only providing a non-existing script does.
compdigit44Author Commented:
Thanks for the feedback.. So you are saying a probably have a type some where???

Also instead of  this powershell c:\temp\ee\get-bigfiles.ps1 -path C:\Temp\EE > C:\temp\ee\get-bigfiles.log

I am using this if it makes a difference powershell c:\temp\ee\get-bigfiles.ps1 -path C:\Temp\EE | export-csv C:\temp\ee\get-bigfiles.log
compdigit44Author Commented:
All ... I think I am have found the trick thanks to this article...

http://www.blogfodder.co.uk/2012/4/20/win-2008-task-scheduler-with-return-code-1-0x1

I am trying thing now and will keep everyone posted...
Qlemo"Batchelor", Developer and EE Topic AdvisorCommented:
The Export-CSV does not make sense. The output of the PS script consists of strings only, and exporting those as CSV will only lead to having the number of characters per string exported ;-). You can use Out-File or >.
But that is not the cause of your issue.
compdigit44Author Commented:
Well..

Following the article I posted before I got the task to run but it is stuck running with the following code (0x41301) it has been in this state for 2 hours and the script should only take 10 minutes to run
compdigit44Author Commented:
I think I am making progress since I can get the task to at least try to run but is stuck with code (0x41301) so far all suggestion I have tried online have not worked. Also I am running the task with the Local admin account..

Please note I get he (0x41301) code when the Start-In box is populate if I do not get the task immediately fails with a (0x1) code
Qlemo"Batchelor", Developer and EE Topic AdvisorCommented:
Is the path you provide local, or UNC/mapped drive?
compdigit44Author Commented:
The path are local on the server and a folder on the root of the C:\ drive . I know it is not a permissions issues since I am running under the local admin account with the check box for run with highest privileges selected.
Qlemo"Batchelor", Developer and EE Topic AdvisorCommented:
We need to know whether the script runs at all. Add
start-transcript $env:temp\script.log

Open in new window

as the first executable line (after param() ). That creates a transcript of the executed commands in the file specified (in the account's temp folder).

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
compdigit44Author Commented:
I updated the script as requested. When I run it via Task Manager I get the same (0x41301) code, When I run it via PowerShell ISE does create a the script. log file..


**********************
Windows PowerShell transcript start
Start time: 20160222201421
Username: Domain\user1
RunAs User: Domain\user1
Machine: Mass1B (Microsoft Windows NT 6.2.9200.0)
Host Application: C:\Windows\System32\WindowsPowerShell\v1.0\powershell_ise.exe C:\Scripts\Test.ps1
Process ID: 22816
**********************
Transcript started, output file is C:\Users\user1\AppData\Local\Temp\3\script.log
compdigit44Author Commented:
Any further suggestions???
Qlemo"Batchelor", Developer and EE Topic AdvisorCommented:
Sorry, we should have used a different folder for writing the log to, like the script folder itself.
Code 0x41301 is "Task is currently running.", which fits to your observation that the script runs endlessly.
That might mean that either PS itself or something in the script leads to getting a confirmation prompt. So try running the task again with a different log file folder for start-transcript. You can also try if -noninteractive to the powershell commandline changes anything (then I expect a failure).
compdigit44Author Commented:
Same result.. Running and not log file in produced in the C:\windows\temp or the temp folder in my profile. I get the same result it the option to run while user is logged in or not
Qlemo"Batchelor", Developer and EE Topic AdvisorCommented:
Did I get that right - you allow the task to run while logged in only, and it still runs endlessly?
compdigit44Author Commented:
Correct!!!!!!
Qlemo"Batchelor", Developer and EE Topic AdvisorCommented:
Very strange. I get that only if the script has to ask for something, and you cannot answer because you do not see anything :/.
Maybe adding -ExecutionPolicy Bypass to the powershell.exe call makes a difference (though it should not). You are not using -noninteractive, I hope?
compdigit44Author Commented:
I was using the -noninteractive switch.;;
Qlemo"Batchelor", Developer and EE Topic AdvisorCommented:
Since it does not work with that option, remove it. You might see more then.
compdigit44Author Commented:
I removed the -noninteractive switch... same result runs endlessly with no log files created..

It is do odd.. The script works fine when I copy and paste by syntax and switches into powershell directly for some reason Task Scheduler  does not like it.
Qlemo"Batchelor", Developer and EE Topic AdvisorCommented:
If you have use neither -noninteractive nor -hidden, and the task is set up to run only when logged on, and the task user is the same as the interactive one, you have to see the PowerShell console window executing the script. Can you confirm that?
compdigit44Author Commented:
I am not using the -noninteractive nor -hidden switches and I am using the option to run the process when logged in...

Please note if I run the exact script from the command line it works perfectly so it is something with Task Scheduler
Qlemo"Batchelor", Developer and EE Topic AdvisorCommented:
Are you seeing the PowerShell console then?
compdigit44Author Commented:
no.... When I right click on the task and select Run is rungs then to the right of it I see 0x41301..

 I have to check tomorrow to see if the Start In box is still populated for the task
compdigit44Author Commented:
Any further idea's on this one?? It is very frustrating and I really appreciate all of your help you have given me...
compdigit44Author Commented:
I have not had a chance to get back to this but out of fairness, I will close this case even though it is still and issue for me and greatly appreciate all the help everyone has provide thus far. :o)
Qlemo"Batchelor", Developer and EE Topic AdvisorCommented:
The only way to find out what is happening is probably to start an interactive cmd.exe calling PowerShell.exe (with no script) as the task's action, then try to execute the script in that shell.
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Powershell

From novice to tech pro — start learning today.