问题
I have Powershell script with some Write-Host
but I want to use it as scheduled task.
I added it as scheduled task with this:
$action = New-ScheduledTaskAction -Execute "$pshome\powershell.exe -WindowStyle Hidden" -Argument "-File $FilePath"
$trigger = New-ScheduledTaskTrigger -Once -At (Get-Date).Date -RepetitionInterval $repeat
Register-ScheduledTask -TaskName $Name -Trigger $trigger -RunLevel Highest -Action $action
Can I make it write to log file? Is it possible to make it write to file at the same location as the Powershell script?
回答1:
There were 2 problems with the script and the 1st was my main problem:
- if it is not signed default behavior is to be sckipped by the Task Scheduler (or at least I didn't saw an error in the Event Viewer).
- I had to use Write-Output
Check if the script is signed with Get-AuthenticodeSignature. Here you are going to receive SignatureStatus as string:
$isSigned = Get-AuthenticodeSignature -FilePath $FilePath | select -ExpandProperty Status
If it is not signed, you can enable the execution of it by adding -ExecutionPolicy Bypass
like it is described in this spiceworks how-to. Do this for your own scripts, because of security !
For the writing part I used Write-Output and Out-File:
(
...
Write-Output "some text here"
...
) | Out-File -FilePath "C:\somepath\log.log
来源:https://stackoverflow.com/questions/62936204/powershell-script-scheduled-task-output-to-log-file