Powershell脚本计划任务输出到日志文件
Powershell script scheduled task output to log file
我有一些 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 脚本相同位置的文件?
脚本有 2 个问题,第一个是我的 main 问题:
- 如果它未签名,默认行为将被任务计划程序跳过(或者至少我没有在事件查看器中看到错误)。
- 我不得不使用 Write-Output
检查脚本是否使用 Get-AuthenticodeSignature. Here you are going to receive SignatureStatus 作为字符串签名:
$isSigned = Get-AuthenticodeSignature -FilePath $FilePath | select -ExpandProperty Status
如果它没有签名,您可以通过添加 -ExecutionPolicy Bypass
来启用它的执行,就像 spiceworks how-to 中描述的那样。为您自己的脚本执行此操作,因为安全!
写作部分我用了Write-Output and Out-File:
(
...
Write-Output "some text here"
...
) | Out-File -FilePath "C:\somepath\log.log
我有一些 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 脚本相同位置的文件?
脚本有 2 个问题,第一个是我的 main 问题:
- 如果它未签名,默认行为将被任务计划程序跳过(或者至少我没有在事件查看器中看到错误)。
- 我不得不使用 Write-Output
检查脚本是否使用 Get-AuthenticodeSignature. Here you are going to receive SignatureStatus 作为字符串签名:
$isSigned = Get-AuthenticodeSignature -FilePath $FilePath | select -ExpandProperty Status
如果它没有签名,您可以通过添加 -ExecutionPolicy Bypass
来启用它的执行,就像 spiceworks how-to 中描述的那样。为您自己的脚本执行此操作,因为安全!
写作部分我用了Write-Output and Out-File:
(
...
Write-Output "some text here"
...
) | Out-File -FilePath "C:\somepath\log.log