2

Log file not being generated while running a PowerShell script via Windows Task Scheduler.

Code as below:

function check-cert
{
  $cmd = "Certutil -crl"
  Invoke-Expression $cmd
  if($LASTEXITCODE -eq '0')
  {
    Write-Output $LASTEXITCODE
  }
  else
  {
    $output = $LASTEXITCODE 
    $date   = (Get-Date).ToString()
    $result = $date + " " + $output
    $result | Out-File "C:\users\admin\Documents\Powershell\crllog.txt" -Append
    Write-Host "crl failed to publish" 
  }
}

check-cert

Could you please help me in getting the log file while running the script via Task Scheduler?

When I run the PowerShell script using the PowerShell editor, the output file gets generated. But when scheduled via Windows Task Scheduler it doesn't.

Ansgar Wiechers
  • 193,178
  • 25
  • 254
  • 328
user2075017
  • 457
  • 4
  • 11
  • 23
  • In what security context (as what user) is the task being run? It may not have access to path `C:\users\admin\Documents\Powershell`. – mklement0 Jun 26 '16 at 20:12
  • HI, i am running it with an admin account on a windows 7 machine as a test, with highest privileges. thank you. – user2075017 Jun 26 '16 at 20:15
  • 2
    And you've verified that `certutil.exe -crl` indeed reports a _nonzero_ exit code in the context of that user? Please add your response - along with the one from your previous comment - _directly to your question_. – mklement0 Jun 26 '16 at 20:20
  • HI, i am running it with an admin account on a windows 7 machine as a test, with highest privileges. thank you. yes, it produces a non zero exit code. – user2075017 Jun 26 '16 at 20:28
  • When i run the powershell script using the powershell editor,the output file gets generated.But when scheduled via windows task scheduler it doesnt. – user2075017 Jun 26 '16 at 21:17
  • 1
    There's not enough information to diagnose your problem - narrow it down further, and add the additional information _directly to your question above, not here as further comments_. – mklement0 Jun 27 '16 at 03:17
  • 2
    If logging to a file fails from a scheduled task it's usually due to a permissions error or because the script fails/hangs before getting to the point where the log would be written. Troubleshooting this is a pain in the rear, though, because you can't interact with the task. Try [logging to the eventlog](https://blogs.technet.microsoft.com/heyscriptingguy/2013/06/20/how-to-use-powershell-to-write-to-event-logs/) instead. – Ansgar Wiechers Jun 27 '16 at 09:31

0 Answers0