Powershell 脚本计划任务输出到日志文件 [英] Powershell script scheduled task output to log file
问题描述
我有一些带有 Write-Host
的 Powershell 脚本,但我想将其用作计划任务.
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
我可以让它写入日志文件吗?是否可以将其写入与 Powershell 脚本相同位置的文件?
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?
推荐答案
脚本有 2 个问题,第一个是我的主要问题:
There were 2 problems with the script and the 1st was my main problem:
- 如果它未签名,则默认行为将被任务计划程序跳过(或者至少我没有在事件查看器中看到错误).
- 我不得不使用写输出
检查脚本是否使用 签名获取 AuthenticodeSignature.在这里,您将收到 SignatureStatus 作为字符串:
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
如果它没有签名,你可以通过添加 -ExecutionPolicy Bypass
来启用它的执行,就像在这个 spiceworks 操作方法.为了安全起见,为您自己的脚本执行此操作!
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
这篇关于Powershell 脚本计划任务输出到日志文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!