简体   繁体   中英

Powershell script scheduled task output to log file

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?

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

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