1
votes

I have a PowerShell (PS) script I want to execute every day at 5:00 a.m. I want to run it to run automatically, so I scheduled it via the Task Scheduler (running Windows 7 Ultimate with SP1, 64-bit). As a test, I wrote a simple PS script that just appends to a text file with a time stamp. It runs--I can see the PowerShell window open and it writes out the PS log--but it doesn't write to the text file.

The script runs fine from the command-line, and from the PS shell. It doesn't work from Task Scheduler, either from the scheduled time or just from the Task Scheduler list and right-clicking and selected Run. Both times it runs, but doesn't write to the text file.

In Task Scheduler, I have the "Actions" set to Start a program, PowerShell.exe. For the "Add arguments", I have: -NoProfile -ExecutionPolicy Bypass -Command C:\AccessTask\ATestScript.ps1

The script is simplicity itself:

Start-Transcript -path "C:\Temp\aTestScript.log" -Verbose

write-output "Start";

# just write one line to file
write-output "Logging";
$text = Get-Date
$text >> 'aTestScriptOutput.txt'

write-output $error[0] | fl -force
write-output "Quit";

Stop-Transcript

Is there something special I have to do to allow a scheduled task to write to a text file?

3
What user is the task running as? Do they have permissions for the file? I note you don't give an absolute path for the file: have you set the startup directory for the task?Richard
Try piping to out-file with appropriate parameters instead of using >>.andyb
Right, what happens if you put a full path e.g C:\temp\aTestScriptOutput.txt (and give everyone:F to C:\temp)Andy Arismendi
Further thought. Specify full path to the log file. Unless you are specifying a 'star in' location in your scheduled task...andyb

3 Answers

2
votes

Adding the full path for the file was the answer:

$text >> 'C:\Temp\aTestScriptOutput.txt'

Specifying a startup directory may have worked as well. Thanks for the help!

1
votes

Scheduled Tasks don't run in the directory of your script. You need to set that directory in the Scheduled Task editor. I believe it is the "Start In" field.

If the output file is always in the same place, you can use a full, absolute path. To improve portability, use a path relative to the script, e.g. Join-Path -Path $PSScriptRoot -ChildPath 'aTestScriptOutput.txt'.

Last recommendation: if your output file will only contain text, pipe output to Set-Content instead of redirecting with >>. The >> operator outputs in UTF-16, which can cause grief when you're trying to view it.

0
votes

You should run the task with the highest privileges (in the task definition) to get it to write to the folder.