はじめに
PowerShellスクリプトにて、スクリプトの実行結果ログを取得する方法についてアウトプットします。
TeraTermでログを取得するようなイメージです。
実行コマンド
ログ取得開始
ログ取得開始
Start-Transcript <ファイル名> -append
「ファイル名」は絶対パスで指定します。
こちらを実行すると、指定したファイル名でログファイルができます。
ログ取得終了
ログ取得終了
Stop-Transcript
ログ取得を終了する際は、こちらのコマンドを実行します。
コマンド実行例
例1
こちらのようなスクリプトを組みます。
test.ps1
$filename = Get-Date -Format "yyyy-MMdd-HHmmss"
Start-Transcript /tmp/ps_log/$filename.log -Append
$test = Get-Host
Write-Output $test
Stop-Transcript
スクリプトの実行結果はこんな感じです。
実行結果
Transcript started, output file is /tmp/ps_log/2020-0719-144610.log
Name : ConsoleHost
Version : 7.0.2
InstanceId : 5a563a75-6c49-44e6-90ff-721d1e97c82b
UI : System.Management.Automation.Internal.Host.InternalHostUserI
nterface
CurrentCulture : ja-JP
CurrentUICulture : ja-JP
PrivateData : Microsoft.PowerShell.ConsoleHost+ConsoleColorProxy
DebuggerEnabled : True
IsRunspacePushed : False
Runspace : System.Management.Automation.Runspaces.LocalRunspace
Transcript stopped, output file is /tmp/ps_log/2020-0719-144610.log
作成されたログの内容は下記になります。
2020-0719-144610.log
**********************
PowerShell transcript start
Start time: 20200719144610
Username: ******************
RunAs User: ****************** ← 本名だったので、伏せています。
Configuration Name:
Machine: **************** (Unix 19.6.0.0)
Host Application: /usr/local/microsoft/powershell/7/pwsh.dll
Process ID: 1162
PSVersion: 7.0.2
PSEdition: Core
GitCommitId: 7.0.2
OS: Darwin 19.6.0 Darwin Kernel Version 19.6.0: Sun Jul 5 00:43:10 PDT 2020; root:xnu-6153.141.1~9/RELEASE_X86_64
Platform: Unix
PSCompatibleVersions: 1.0, 2.0, 3.0, 4.0, 5.0, 5.1.10032.0, 6.0.0, 6.1.0, 6.2.0, 7.0.2
PSRemotingProtocolVersion: 2.3
SerializationVersion: 1.1.0.1
WSManStackVersion: 3.0
**********************
Transcript started, output file is /tmp/ps_log/2020-0719-144610.log
Name : ConsoleHost
Version : 7.0.2
InstanceId : 5a563a75-6c49-44e6-90ff-721d1e97c82b
UI : System.Management.Automation.Internal.Host.InternalHostUserI
nterface
CurrentCulture : ja-JP
CurrentUICulture : ja-JP
PrivateData : Microsoft.PowerShell.ConsoleHost+ConsoleColorProxy
DebuggerEnabled : True
IsRunspacePushed : False
Runspace : System.Management.Automation.Runspaces.LocalRunspace
**********************
PowerShell transcript end
End time: 20200719144610
**********************
例2
ログの保存開始/終了表示を非表示にしたい場合は、Out-Null
を使用します。
test2.ps1
$filename = Get-Date -Format "yyyy-MMdd-HHmmss"
Start-Transcript /tmp/ps_log/$filename.log -Append | Out-Null
$test = Get-Host
Write-Output $test
Stop-Transcript | Out-Null
スクリプト実行結果は、こちらになります。
実行結果
Name : ConsoleHost
Version : 7.0.2
InstanceId : 5a563a75-6c49-44e6-90ff-721d1e97c82b
UI : System.Management.Automation.Internal.Host.InternalHostUserI
nterface
CurrentCulture : ja-JP
CurrentUICulture : ja-JP
PrivateData : Microsoft.PowerShell.ConsoleHost+ConsoleColorProxy
DebuggerEnabled : True
IsRunspacePushed : False
Runspace : System.Management.Automation.Runspaces.LocalRunspace