简体   繁体   中英

Scheduled PowerShell task won't write to file

I have a PowerShell (PS) script I want to execute every day at 5:00 am 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?

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!

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, eg 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.

您应该以最高特权(在任务定义中)运行任务,以使其写入文件夹。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM