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

时间:2012-12-09 03:35:22

标签: powershell scheduled-tasks line-endings

从Task Scheduler运行简单的PowerShell脚本时,我想将输出重定向到文件。

关于这个主题here有一个很长的线索,但是到目前为止它们是否达到了最合适的解决方案还不清楚。我很感兴趣,如果SO上的任何人也解决了这个问题,以及他们是如何做到的。

10 个答案:

答案 0 :(得分:32)

这是对我有用的命令。我不喜欢在脚本中重定向输出的想法,因为这会使手动运行变得困难。

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

答案 1 :(得分:29)

我使用Transcript功能来帮助解决这个问题。只需将其包含在您的代码中,它就会将所有(可能的)屏幕内容输出到日志文件中。

    Start-Transcript -path $LogFile -append

    <body of script>

    Stop-Transcript

答案 2 :(得分:16)

以下适用于Windows 7:

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

在win7任务计划程序gui中:

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

请注意,“ - file”不起作用,因为文件名后面的所有参数都被解释为文件的参数。 注意,“2&gt;&amp; 1”也将错误输出重定向到日志文件。 powershell的后续版本以稍微不同的方式执行此操作。

答案 3 :(得分:1)

我应该这样做: 创建一个函数来调用你的脚本并重定向这个函数的输出,如下所示:

.ps1:

function test{
    #your simple script commands
    ls c:\temp -Filter *.JPG
    ls z:\ #non existent dir
}

test *> c:\temp\log.txt 

这是日志文件:

    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

您可以使用新的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

答案 4 :(得分:1)

我在 Windows Server 2016 上测试了以下内容,只调用 powershell 一次。这样你就可以有一个带空格的文件夹名称:

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

答案 5 :(得分:0)

我意识到这已经回答了几次,但上述所有答案的组合确实帮助了我......

我的问题是我需要在WinRM上执行Powershell脚本作为Packer配置程序的一部分,并且由于权限问题它仍然失败。解决这个问题的方法是作为计划任务执行,但我需要将参数传递给脚本并获取输出以确认一切都已通过。

这段代码对我有用:

# 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)

完整的脚本可以在这里找到:

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

答案 6 :(得分:0)

使用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
Stop-Transscript

日志文件将与脚本位于同一目录中。

答案 7 :(得分:0)

wards上的Powershell 3允许重定向各个流(out,verbose,error)。但是,任务计划程序不理解它们。它是执行重定向的powershell。

@ cmcginty的解决方案中途工作,因为powershell正在调用powershell,它只支持标准流(错误,输出)。如果您想使用所有需要使用的拉绳

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

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

开始于:path_to_ps1

答案 8 :(得分:0)

我受到来自Anders的评论问题(如何添加时间戳?)以及两次调用PowerShell的多次答复的启发而写了这个答案,我认为这不是必需的。任务计划程序显然是“ powershell.exe”,对于这些参数,我将简单建议一下:

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

要每天保留一个文件,然后:

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

如果您确实想要带有时间戳的日志文件,则可以删除第二个“>”(两个表示追加到任何现有文件中)并扩展时间格式:

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

答案 9 :(得分:-1)

这个发送详细信息输出屏幕并将其记录到文件中 需要一段时间来弄明白,所以这个线程似乎是最合适的地方

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