[英]Powershell Logging within modules and dot sourced scripts
我在.psm1文件中存儲了一些功能,該文件由幾個不同的ps1腳本使用。 我創建了一個日志記錄功能(如下所示),在整個這些ps1腳本中都使用了該功能。 通常,我可以通過簡單地調用以下命令將模塊導入腳本中:
Import-Module $PSScriptRoot\Module_Name.psm1
然后在模塊中,我有一個寫記錄器功能:
Write-Logger -Message "Insert log message here." @logParams
整個主腳本和模塊本身都使用此功能。 @logParams
參數@logParams
是在我的主.ps1文件中定義的,並且未顯式傳遞給模塊,我假設變量在導入時隱式位於模塊范圍內。 我的作品行得通,但我覺得這不是一個好習慣。 最好在模塊中添加一個param
塊,以要求從.ps1主腳本中顯式傳遞@logParams
嗎? 謝謝!
function Write-Logger() {
[cmdletbinding()]
Param (
[Parameter(Mandatory=$true)]
[string]$Path,
[Parameter(Mandatory=$true)]
[string]$Message,
[Parameter(Mandatory=$false)]
[string]$FileName = "Scheduled_IDX_Backup_Transcript",
[switch]$Warning,
[switch]$Error
)
# Creates new log directory if it does not exist
if (-Not (Test-Path ($path))) {
New-Item ($path) -type directory | Out-Null
}
if ($error) {
$label = "Error"
}
elseif ($warning) {
$label = "Warning"
}
else {
$label = "Normal"
}
# Mutex allows for writing to single log file from multiple runspaces
$mutex = new-object System.Threading.Mutex $false,'MutexTest'
[void]$mutex.WaitOne()
Write-Host "$(Format-LogTimeStamp) $label`: $message"
"$(Format-LogTimeStamp) $label`: $message" | Out-file "$path\$fileName.log" -encoding UTF8 -append
[void]$mutex.ReleaseMutex()
}
我在ps1中有這段代碼,可以將源點到要生成自己的日志的腳本中。 ps1包含simpleLogger
類以及下面的創建全局變量的例程。 腳本可以再次以點為源,並將全局變量值傳遞給隨后產生的作業以維護單個日志文件。
class simpleLogger
{
[string]$source
[string]$target
[string]$action
[datetime]$datetime
hidden [string]$logFile = $global:simpleLog
simpleLogger()
{
$this.datetime = Get-Date
}
simpleLogger( [string]$source, [string]$target, [string]$action )
{
$this.action = $action
$this.source = $source
$this.target = $target
$this.datetime = Get-Date
}
static [simpleLogger] log( [string]$source, [string]$target, [string]$action )
{
$newLogger = [simpleLogger]::new( [string]$source, [string]$target, [string]$action )
do {
$done = $true
try {
$newLogger | export-csv -Path $global:simpleLog -Append -NoTypeInformation
}
catch {
$done = $false
start-sleep -milliseconds $(get-random -min 1000 -max 10000)
}
} until ( $done )
return $newLogger
}
}
if( -not $LogSession ){
$global:logUser = $env:USERNAME
$global:logDir = $env:TEMP + "\"
$startLog = (get-date).tostring("MMddyyyyHHmmss")
$global:LogSessionGuid = (New-Guid)
$global:simpleLog = $script:logDir+$script:logUser+"-"+$LogSessionGuid+".log"
[simpleLogger]::new() | export-csv -Path $script:simpleLog -NoTypeInformation
$global:LogSession = [simpleLogger]::log( $script:logUser, $LogSessionGuid, 'Log init' )
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.