51

从任务计划程序运行一个简单的 PowerShell 脚本时,我想将输出重定向到一个文件。

这里有一个关于这个主题的长线程,但不清楚他们最终是否达到了最合适的解决方案。我很感兴趣 Stack Overflow 上是否有人也解决了这个问题,他们是如何解决的?

4

10 回答 10

41

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

powershell -windowstyle minimized -c "powershell -c .\myscript.ps1 -verbose >> \\server\myscript.log 2>&1"
于 2012-12-11T20:20:15.047 回答
41

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

Start-Transcript -path $LogFile -append

<Body of the script>

Stop-Transcript
于 2013-06-24T08:22:37.220 回答
24

以下适用于我在 Windows 7 上:

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

在 Windows 7 任务计划程序 GUI 中:

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

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

于 2014-03-04T06:58:18.927 回答
4

之前所有答案的组合确实帮助了我......

我的问题是我需要在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

于 2017-01-11T11:08:06.703 回答
2

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

.ps1:

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

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
于 2012-12-09T07:36:29.413 回答
2

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

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

于 2018-01-26T09:55:21.187 回答
2

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

Powershell.exe -NoProfile -ExecutionPolicy Bypass -WindowStyle minimized "scriptName.ps1 *>> '\\servername\sharename\folder name with space\logfilename.log'"
于 2021-01-25T03:27:06.737 回答
0

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

于 2018-06-08T21:59:46.300 回答
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"
于 2020-11-16T18:37:10.533 回答
-1

下面将详细输出发送到屏幕并将其记录到文件中。

something you're doing -Verbose 4>&1 | Tee-Object "C:\logs\verb.log" -Append
于 2016-07-20T22:30:04.327 回答