Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/powershell/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
从任务计划程序运行时,如何重定向PowerShell输出?_Powershell_Scheduled Tasks_Line Endings - Fatal编程技术网

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

从任务计划程序运行时,如何重定向PowerShell输出?,powershell,scheduled-tasks,line-endings,Powershell,Scheduled Tasks,Line Endings,从Task Scheduler运行简单的PowerShell脚本时,我希望将输出重定向到一个文件 关于这个主题有一个很长的线索,但不清楚他们最终是否找到了最合适的解决方案。我很感兴趣StackOverflow上是否有人也解决了这个问题,以及他们是如何解决的?我会这样做: 创建一个函数来调用脚本并重定向此函数的输出,如下所示: .ps1: 以下是日志文件: Répertoire : C:\temp Mode LastWriteTime Length

从Task Scheduler运行简单的PowerShell脚本时,我希望将输出重定向到一个文件

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

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

.ps1: 以下是日志文件:

    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

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

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

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

Start-Transcript -path $LogFile -append

<Body of the script>

Stop-Transcript
Start Transcript-path$LogFile-append
停止记录

以下内容在Windows7上适用于我:

 powershell -command c:\temp\pscript.ps1 2>&1 > c:/temp/apickles.log
在Windows7任务计划程序GUI中:

 program = "Powershell"
 arguments = "-command c:\temp\pscript.ps1 2>&1 > c:/temp/apickles.log"
请注意,“-file”不起作用,因为文件名后的所有参数都被解释为文件的参数。
请注意,“2>&1”也会将错误输出重定向到日志文件。更高版本的PowerShell以稍微不同的方式执行此操作。

下面的内容将详细输出发送到屏幕,并将其记录到文件中

您正在做的事情-verbose4>&1 | Tee对象“C:\logs\verb.log”-追加

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

我的问题是,我需要作为打包程序provisioner的一部分执行PowerShell脚本,但由于权限问题,它一直失败。解决这个问题的方法是作为计划任务执行,但我需要将参数传递给脚本,并获得输出,以确认传递的所有内容

这段代码对我很有用:

# 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)
完整脚本可在此处找到:


直接登录到文件可能更容易使用:

# 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

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

PowerShell 3以后的版本允许重定向单个流(out、verbose和error)。但是,任务调度器不理解它们。是PowerShell执行重定向

因为PowerShell正在调用PowerShell,所以这一过程已经完成了一半。它只支持标准流(错误和输出)。如果要使用所有需要使用的流,请使用:

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

参数:
-windowstyle最小化–非交互式–NoProfile-c“powershell-c路径到\u ps1.ps1 4>>verbose.log 5>>debug.log”


从:
path\u to_ps1

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"

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

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

您可能希望使用-Noninteractive来避免任何提示。如何为此添加时间戳?如果有人知道如何处理文件路径中的空格,我很想知道如何添加时间戳。我无法让解析器正确解析双引号、单引号或转义引号。这看起来像是从powershell中调用powershell?是的,就像@JamieHanrahan注意到的,两次调用powershell的目的是什么?但是*>在从计划任务运行时起作用吗?因为这个问题暗示它不是。谢谢你对Windows7任务调度器GUI“参数”的评论-我想这是放置输出重定向选项的正确位置。其他答案都没有提到这一点。-win10为1。它在windows 10中对我不起作用。这篇文章也有同样的问题。“-Command”的一个缺点是它是被解释的,所以在ps1文件的路径中的空格或任何可解释的内容都会将其转化为错误。因此,最好单独设置工作目录,只为
-Command
使用一个(非特殊字符)文件名。在GUI中,不要在输入字段中添加引号,只在它们之间写入内容(如上)。使用工作目录而不是日志文件的路径。当我启动命令表单任务计划程序(作为powershell.exe的参数)时,我看到转录本的不同行为。具体来说,调用Write Host似乎会将我的文本发送到转录本无法捕获的某个位置,尽管重定向到Out Host似乎有效。我正在Windows Server 2012 R2上运行PowerShell 4.0,如果有必要的话。我必须使用写输出,而不是写主机。@JayCarlton你不应该使用写主机,而是写输出,正如PowerShell的创建者所说:也就是说,我还没有测试它是否会对你的日志产生影响,但它应该会。酷,我的powershell脚本似乎也没有从任务计划程序在注册表中执行任何操作(由于权限),也无法在启用上述日志记录的情况下写入磁盘。以我的用户身份运行,是否具有“以最大功能运行”权限
Powershell.exe -NoProfile -ExecutionPolicy Bypass -WindowStyle minimized "scriptName.ps1 *>> '\\servername\sharename\folder name with space\logfilename.log'"