【问题标题】:Powershell script scheduled task output to log filePowershell脚本计划任务输出到日志文件
【发布时间】:2020-11-06 05:04:08
【问题描述】:

我有一些带有 Write-Host 的 Powershell 脚本,但我想将其用作计划任务。

我将它添加为计划任务:

$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

我可以让它写入日志文件吗?是否可以使其写入与 Powershell 脚本位于同一位置的文件?

【问题讨论】:

  • 是的,要么使用 Out-File cmdlet,要么您可以安排脚本将输出重定向到文件 .\script.ps1 > scriptOut.log 您也可以同时使用 stout 和 sterr。 .\script.ps1 > script_out.log 2>&1
  • 您是否尝试将Write-Host 语句更改为Out-FileAdd-Content?当前脚本的位置可以从$PsScriptRoot变量中获取。
  • 两个建议最终都显示“你想如何打开这个文件”模式
  • @Gerhard 我在 Powershell 控制台中使用过它。在计划任务中,它使用-WindowStyle Hidden 执行。这会导致奇怪的行为吗?
  • 嗯,这只是一个例子。我建议你改用Out-File cmdlet。

标签: powershell scheduled-tasks


【解决方案1】:

脚本有 2 个问题,第一个是我的主要问题:

  1. 如果未签名默认行为将被任务计划程序跳过(或者至少我没有在事件查看器中看到错误)。
  2. 我不得不使用写输出

检查脚本是否使用Get-AuthenticodeSignature 签名。在这里,您将收到SignatureStatus 作为字符串:

$isSigned = Get-AuthenticodeSignature -FilePath $FilePath | select -ExpandProperty Status

如果它没有签名,你可以通过添加-ExecutionPolicy Bypass 来启用它的执行,就像在这个spiceworks how-to 中描述的那样。出于安全考虑,为您自己的脚本执行此操作!


写作部分我使用了Write-OutputOut-File

(
   ...
   Write-Output "some text here"
   ...
) | Out-File -FilePath "C:\somepath\log.log

【讨论】:

    猜你喜欢
    • 2023-02-21
    • 2017-09-28
    • 1970-01-01
    • 1970-01-01
    • 2019-05-02
    • 1970-01-01
    • 2011-02-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多