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

以下は、Windows7で動作します。

 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

以前のすべての答えの組み合わせは本当に私を助けました...

私の問題は、Packerプロビジョナーの一部としてWinRM上で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)

完全なスクリプトはここにあります:

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

私はWindowsServer2016で以下をテストしましたが、一度だけ呼び出します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です。

PowerShellがPowerShellを呼び出しているため、@cmcgintyのソリューションは途中で機能します。標準ストリーム(エラーおよび出力)のみをサポートします。すべてのストリームを使用する場合は、以下を使用する必要があります。

プログラムまたはスクリプト: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を2回呼び出す複数の応答によって、この回答を書くように促されました。これは必須ではないと主張します。タスクスケジューラプログラムは明らかに「powershell.exe」であり、引数については簡単に提案します。

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

1日あたりのファイルを保持するには、次のようにします。

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

また、タイムスタンプ付きのログファイルが必要な場合は、2番目の ">"(2つは既存のファイルへの追加を示します)を削除し、時間形式を拡張できます。

-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 に答える