简体   繁体   English

从任务计划程序运行时如何重定向 PowerShell 输出?

[英]How can I redirect PowerShell output when run from Task Scheduler?

When running a simple PowerShell script from Task Scheduler, I would like to redirect the output to a file.从任务计划程序运行简单的 PowerShell 脚本时,我想将输出重定向到一个文件。

There is a long thread about this very topic here , yet it's not clear if they reached the most appropriate solution in the end.关于这个话题这里有一个很长的话题,但尚不清楚他们最终是否找到了最合适的解决方案。 I'm interested if anyone on Stack Overflow has also solved this problem, and how they did it?我想知道 Stack Overflow 上是否有人也解决了这个问题,他们是如何解决的?

I use the transcript feature to help with this.我使用成绩单功能来帮助解决这个问题。 Just include it in your code and it outputs all (would be) screen content to a log file.只需将它包含在您的代码中,它就会将所有(将是)屏幕内容输出到一个日志文件中。

Start-Transcript -path $LogFile -append

<Body of the script>

Stop-Transcript

Here is the command that worked for me.这是对我有用的命令。 I didn't like the idea of redirecting the output in the script, since it would make it difficult to run manually.我不喜欢在脚本中重定向输出的想法,因为这会使手动运行变得困难。

powershell -windowstyle minimized -c "powershell -c .\myscript.ps1 -verbose >> \\server\myscript.log 2>&1"

The following works for me on Windows 7:以下适用于 Windows 7:

 powershell -command c:\temp\pscript.ps1 2>&1 > c:/temp/apickles.log

In the Windows 7 Task Scheduler GUI:在 Windows 7 任务计划程序 GUI 中:

 program = "Powershell"
 arguments = "-command c:\temp\pscript.ps1 2>&1 > c:/temp/apickles.log"

Note that "-file" does not work because all parameters after the file name are interpreted as parameters to the file.请注意,“-file”不起作用,因为文件名后的所有参数都被解释为文件的参数。 Note that "2>&1" redirects the error output to the log file as well.请注意,“2>&1”也将错误输出重定向到日志文件。 Later versions of PowerShell do this in a slightly different way. PowerShell 的更高版本以稍微不同的方式执行此操作。

A combination of all the previous answers really helped me out...以前所有答案的组合确实帮助了我......

My problem was that I needed to execute a PowerShell script over WinRM as part of a Packer provisioner, and it kept failing due to rights issues.我的问题是我需要在WinRM上执行一个 PowerShell 脚本作为 Packer 供应器的一部分,并且由于权限问题它一直失败。 The way around this is to execute as a scheduled task, but I needed to pass arguments to the script and get the output as well to confirm everything passed.解决这个问题的方法是作为计划任务执行,但我需要将参数传递给脚本并获取输出以确认一切都已通过。

This snippet worked well for me:这个片段对我来说效果很好:

# Generate a unique ID for this execution
$guid = [guid]::NewGuid()
$logFile = "C:\Windows\Temp\$guid.log"

$argument = "-NoProfile -ExecutionPolicy unrestricted -Command ""& {""$ScriptPath"" $ScriptArgs} 2>&1 > $logFile"""

$a = New-ScheduledTaskAction -Execute "powershell.exe" -Argument $argument
Register-ScheduledTask -TaskName $TaskName  -RunLevel Highest -User $username -Password $password -Action $a | Start-ScheduledTask
do {
    Start-Sleep -Seconds 30
    $task = Get-ScheduledTask -TaskName $TaskName
} while ($task.State -eq 4)

The full script can be found here:完整的脚本可以在这里找到:

https://gist.github.com/dev-rowbot/fa8b8dadf1b3731067a93065db3e1bba https://gist.github.com/dev-rowbot/fa8b8dadf1b3731067a93065db3e1bba

It would be maybe easier to use Start-Transcript in order to log directly to a file:为了直接登录到文件,使用Start-Transcript可能会更容易:

# Get script name
$ScriptFullPath = $MyInvocation.MyCommand.Path
# Start logging stdout and stderr to file
Start-Transcript -Path "$ScriptFullPath.log" -Append

[Some PowerShell commands]

# Stop logging to file
Stop-Transcript

The log file will be in the same directory as the script.日志文件将与脚本位于同一目录中。

I would do:我会做:
Create a function to call your script and redirect the output of this function like this:创建一个函数来调用您的脚本并重定向此函数的输出,如下所示:

.ps1: .ps1:

function test{
    # Your simple script commands
    ls c:\temp -Filter *.JPG
    ls z:\ # Non-existent directory
}

test *> c:\temp\log.txt

Here is the log file:这是日志文件:

    Répertoire : C:\temp


Mode                LastWriteTime     Length Name
----                -------------     ------ ----
-a---        07/06/2008     11:06     176275 HPIM1427.JPG
-a---        07/06/2008     11:06      69091 HPIM1428.JPG
-a---        07/06/2008     11:06     174661 HPIM1429.JPG


ls : Lecteur introuvable. Il n'existe aucun lecteur nommé « z ».
Au caractère C:\temp\test.ps1:14 : 1
+ ls z:\ #non existent dir
+ ~~~~~~
    + CategoryInfo          : ObjectNotFound: (z:String) [Get-ChildItem], Driv
   eNotFoundException
    + FullyQualifiedErrorId : DriveNotFound,Microsoft.PowerShell.Commands.GetC
   hildItemCommand

You can control what do you want to output with the new V3 redirection operators:您可以使用新的 V3 重定向运算符控制要输出的内容:

Do-Something 3> warning.txt  # Writes warning output to warning.txt
Do-Something 4>> verbose.txt # Appends verbose.txt with the verbose output
Do-Something 5>&1            # Writes debug output to the output stream
Do-Something *> out.txt      # Redirects all streams (output, error, warning, verbose, and debug) to out.txt

I tested the following on Windows Server 2016, only call powershell once.我在 Windows Server 2016 上测试了以下内容,只调用了一次powershell This way you can have folder names with a space:这样你就可以拥有带空格的文件夹名称:

Powershell.exe -NoProfile -ExecutionPolicy Bypass -WindowStyle minimized "scriptName.ps1 *>> '\\servername\sharename\folder name with space\logfilename.log'"

PowerShell 3 onwards allows individual streams (out, verbose, and error) to be redirected. PowerShell 3 及更高版本允许重定向单个流(输出、详细和错误)。 However, Task Scheduler does not understand them.然而,Task Scheduler 不理解它们。 It's PowerShell that does the redirection.执行重定向的是 PowerShell。

@cmcginty's solution halfway works, since PowerShell is invoking PowerShell. @cmcginty 的解决方案半途而废,因为 PowerShell 正在调用 PowerShell。 It only supports standard streams (error and out).它仅支持标准流(错误和输出)。 If you want to use all streams you need to use:如果你想使用你需要使用的所有流:

Program or script: C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe程序或脚本: C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe

Argument: -windowstyle minimized –NonInteractive –NoProfile -c "powershell -c path_to_ps1.ps1 4>>verbose.log 5>>debug.log"参数: -windowstyle minimized –NonInteractive –NoProfile -c "powershell -c path_to_ps1.ps1 4>>verbose.log 5>>debug.log"

Start in: path_to_ps1开始于: path_to_ps1

I'm inspired to write this answer by a comment-question from Anders (How do you add a timestamp?), and by the multiple replies that invoke PowerShell twice, which I would argue is not required.我写这个答案的灵感来自 Anders 的评论问题(你如何添加时间戳?),以及两次调用 PowerShell 的多个回复,我认为这不是必需的。 The task scheduler program is clearly "powershell.exe" and for the arguments I would suggest simply:任务调度程序显然是“powershell.exe”,对于参数我会简单地建议:

-noninteractive -c "scriptpath.ps1 *>>logpath.txt"

To keep a file per day, then:要每天保留一个文件,则:

-noninteractive -c "scriptpath.ps1 *>>logpath-$((get-date).ToString('yyyy-MM-dd')).txt"

And if you do want a log file with timestamp, you could remove the second ">" (two indicating append to any existing file) and expand the time format:如果你确实想要一个带有时间戳的日志文件,你可以删除第二个“>”(两个表示附加到任何现有文件)并扩展时间格式:

-noninteractive -c "scriptpath.ps1 *>logpath-$((get-date).ToString('yyyy-MM-dd_HH-mm-ss-fff')).txt"

The below sends verbose output to the screen as well as log it to a file.下面将详细输出发送到屏幕并将其记录到文件中。

something you're doing -Verbose 4>&1 | Tee-Object "C:\logs\verb.log" -Append

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何重定向批处理文件中的Powershell输出(从Task Scheduler运行时)? - How to redirect powershell output within batch file ( when run from Task Scheduler)? 从任务计划程序运行时,PowerShell脚本失败 - PowerShell script failing when run from the Task Scheduler 如何说服 powershell(通过任务调度程序运行)找到我的网络驱动器? - How can I convince powershell (run through task scheduler) to find my network drive? 我无法让 powershell 在任务计划程序中运行 - I cant get powershell to run in task scheduler 如何在任务计划程序中显示Powershell运行屏幕? - how can i show up powershell running screen in task scheduler? 如何通过Powershell和Task Scheduler记录所有DNS请求? - How can i log all dns request by powershell and task scheduler? 如何使用 powershell 脚本禁用任务调度程序作业 - How can i disable task scheduler jobs using powershell script Excel 宏通过 powershell 运行,但在 Windows 任务计划程序运行时不运行 - Excel macros run through powershell but not when run by windows task scheduler 如何从Powershell重定向输出 - How Do I Redirect Output From Powershell 如何使用 PowerShell 从任务计划程序中删除文件夹? - How to delete folder from Task Scheduler with PowerShell?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM