出力をファイルにリダイレクトしたいPowerShellスクリプトがあります。問題は、このスクリプトの呼び出し方法を変更できないことです。だから私はできません:
.\MyScript.ps1 > output.txt
PowerShellスクリプトの実行中にPowerShellスクリプトの出力をリダイレクトするにはどうすればよいですか?
出力をファイルにリダイレクトしたいPowerShellスクリプトがあります。問題は、このスクリプトの呼び出し方法を変更できないことです。だから私はできません:
.\MyScript.ps1 > output.txt
PowerShellスクリプトの実行中にPowerShellスクリプトの出力をリダイレクトするにはどうすればよいですか?
多分Start-Transcript
あなたのために働くでしょう。すでに実行されている場合は最初に停止し、次に開始し、完了したら停止します。
$ ErrorActionPreference = "SilentlyContinue" 停止-トランスクリプト| アウトヌル $ ErrorActionPreference="続行" Start-Transcript -path C:\ output.txt -append #何かをする 停止-トランスクリプト
作業中にこれを実行して、後で参照できるようにコマンドラインセッションを保存することもできます。
転写されていない転写物を停止しようとしたときにエラーを完全に抑制したい場合は、次のようにすることができます。
$ErrorActionPreference="SilentlyContinue"
Stop-Transcript | out-null
$ErrorActionPreference = "Continue" # or "Stop"
Microsoftは、PowershellのConnections Webサイト(2012-02-15 at 4:40 PM)で、バージョン3.0で、この問題の解決策としてリダイレクトを拡張したことを発表しました。
In PowerShell 3.0, we've extended output redirection to include the following streams:
Pipeline (1)
Error (2)
Warning (3)
Verbose (4)
Debug (5)
All (*)
We still use the same operators
> Redirect to a file and replace contents
>> Redirect to a file and append to existing content
>&1 Merge with pipeline output
詳細と例については、「about_Redirection」ヘルプ記事を参照してください。
help about_Redirection
使用する:
Write "Stuff to write" | Out-File Outputfile.txt -Append
私はあなたが変更できると思いますMyScript.ps1
。次に、次のように変更してみてください。
$(
Here is your current script
) *>&1 > output.txt
PowerShell 3でこれを試しました。NathanHartleyの回答のように、すべてのリダイレクトオプションを使用できます。
powershell ".\MyScript.ps1" > test.log
あなたの状況がそれを許すならば、1つの可能な解決策:
次のような新しいMyScript.ps1を作成します。
。\TheRealMyScript.ps1>output.txt
すべての出力をファイルに直接リダイレクトする場合は、次を使用してみてください*>>
。
# You'll receive standard output for the first command, and an error from the second command.
mkdir c:\temp -force *>> c:\my.log ;
mkdir c:\temp *>> c:\my.log ;
これはファイルへの直接のリダイレクトであるため、コンソールに出力されません(多くの場合役立ちます)。コンソール出力が必要な場合は、すべての出力を*&>1
、と組み合わせてから、パイプを使用しTee-Object
ます。
mkdir c:\temp -force *>&1 | Tee-Object -Append -FilePath c:\my.log ;
mkdir c:\temp *>&1 | Tee-Object -Append -FilePath c:\my.log ;
# Shorter aliased version
mkdir c:\temp *>&1 | tee -Append c:\my.log ;
これらの手法はPowerShell3.0以降でサポートされていると思います。PowerShell5.0でテストしています。
コマンドレットTee-Objectを確認することをお勧めします。出力をTeeにパイプすると、パイプラインとファイルに書き込まれます。
スクリプト自体に組み込まれずにコマンドラインから実行する場合は、次を使用します。
.\myscript.ps1 | Out-File c:\output.csv
これをスクリプトに埋め込むには、次のようにします。
Write-Output $server.name | Out-File '(Your Path)\Servers.txt' -Append
それでうまくいくはずです。