Powershell script scheduled task output to log file

血红的双手。 提交于 2021-02-11 13:56:33

问题


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:

  1. 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).
  2. 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!