Powershell: タイムスタンプを作る

コマンドや、結果を出力した時刻を、結果と一緒に記録しておきたい場合があります。厳密にはタイムスタンプと、コマンド実行は数秒ずれる場合がありますが目印にはなります。

Powershell の場合、Get-Date コマンドを使います。日本語環境のデフォルトの出力形式は、データ処理をするのに向いていないため、Formatオプションで形式を細かく指定。

わざわざメモとして公開するほどの情報ではないのですが、毎回検索したりヘルプコマンドで確認するのも面倒なので、将来の copy & paste で再利用できるように記録に残しておくことにします。

$timestamp = (Get-Date -Format "yy/MM/dd HH:mm:ss")
$timestamp

では、どういう使い方をするかというと、以下のような感じ。(変数に入れる必要はないのですけどね。)

$c = Get-Credential

$logfile = "output.txt"
cd C:\temp

while(1){
    $timestamp = (Get-Date -Format "yy/MM/dd HH:mm:ss")
    $timestamp|Tee-Object -Append -FilePath $logfile
    gwmi -ComputerName win10_01 -Credential $c Win32_PerfFormattedData_PerfOS_Processor | Select Name,PercentProcessorTime |Out-String |Tee-Object -Append -FilePath $logfile
    gwmi -ComputerName win10_01 -Credential $c Win32_OperatingSystem | %{(($_.TotalVisibleMemorySize - $_.FreePhysicalMemory)/$_.TotalVisibleMemorySize) * 100}|Tee-Object -Append -FilePath $logfile
    #gwmi -ComputerName win10_01 -Credential $c win32_process | select ProcessId,Name,CommandLine |Out-String|Tee-Object -Append -FilePath $logfile
    sleep 10
}

出力結果は、以下の通り。

20/01/01 14:16:49

Name   PercentProcessorTime
----   --------------------
0                        23
1                        17
2                         0
3                         0
_Total                   10



30.7302966691165
20/01/01 14:17:04

Name   PercentProcessorTime
----   --------------------
0                         5
1                         0
2                         5
3                         0
_Total                    2



30.739538393006

 

コメントを残す