[PowerShell] 進行日誌記錄

為了令troubleshooting 可以有更多資料, logging 是其中一種手段. 在寫code時, 可以利用log4J 或log4net 去實現. 但在寫Script 時, 則須要自己處理.

因此, 在PowerShell 中, 寫了一個function 去進行logging 如下:

$logFilePath="C:\Temp\log_"+$executeDateFormat+".log"

function Write-Log($content)
{
	Write-Debug $content
    $logDateTime=Get-Date
	Add-Content $logFilePath -value "[$logDateTime] $content"
}

Write-Log "Hello World!!!"

它除了將內容寫到log file外, 還會於PowerShell 的debug mode 中顯示出來, 方便嘗試reproduce 錯誤以作進一步的診斷.

然而, 要留要log path 若會寫入folder內的話, 須要先行設好, 否則會throw exception. 

About C.H. Ling 262 Articles
a .net / Java developer from Hong Kong and currently located in United Kingdom. Thanks for Google because it solve many technical problems so I build this blog as return. Besides coding and trying advance technology, hiking and traveling is other favorite to me, so I will write down something what I see and what I feel during it. Happy reading!!!

Be the first to comment

Leave a Reply

Your email address will not be published.


*


This site uses Akismet to reduce spam. Learn how your comment data is processed.