2017-08-03 50 views
2

我收集了一些PowerShell腳本,其中一些調用了其他腳本。其中一些下標也可以根據需要自行調用。如何快速將日誌記錄添加到所有腳本中,以便任何腳本調用生成日誌文件供以後檢查?將日誌記錄快速添加到現有的PowerShell腳本集

有一些問題與日誌記錄有一些很好的答案,like this one。但是,我想看看我們能想出是:

  • 需要對現有的PowerShell文件
  • 自動處理腳本A.ps1調用腳本B.ps1的最小感人。如果您撥打 A.ps1,A.ps1需要開始並結束記錄。但如果你直接撥打B.ps1 ,B.ps1就可以。

我在下面提出了我的答案,並且想分享一下,看看有沒有關於如何解決這個問題的其他想法,或者對我的答案有什麼改進建議。

+1

[或者你可以打開自動腳本日誌(https://blogs.msdn.microsoft.com/powershell/2015/06/09/powershell -the-藍隊/) –

回答

2

我編寫的支持代碼(進一步向下)允許將以下內容添加到每個ps1文件。它會自動給出不管如果腳本被稱爲在頂層或其他腳本我登錄:

#any params for script 
. "$PSScriptRoot\ps_support.ps1" 
StartTranscriptIfAppropriate 
try 
{ 
#all of the original script 
} 
finally 
{ 
ConditionalStopTranscript 
} 

的代碼的權力,這是在ps_support.ps1,坐在旁邊的我的收藏需要記錄的PowerShell文件。它使用Get-變量,並將變量在調用者的範圍級別操縱幾個變量:

  • Logging__TranscriptStarted是正常的這樣子範圍可以看出, 記錄已經發生,不要試圖再次啓動它。
  • Logging__TranscriptStartedPrivate是私有的,因此範圍可以知道它是否負責停止日誌記錄。

這裏是ps_support.ps1:

Set-Variable -name TranscriptStartedPropertyName -opt ReadOnly -value 'Logging__TranscriptStarted' 
Set-Variable -name TranscriptStartedPrivatePropertyName -opt ReadOnly -value 'Logging__TranscriptStartedPrivate' 

function StartTranscriptIfAppropriate 
{ 
    $transcriptStarted = [bool](Get-Variable -name $TranscriptStartedPropertyName -ErrorAction Ignore) 
    if (-not $transcriptStarted) 
    { 
     $callstack = get-pscallstack 
     $fullPath = $callstack[$callstack.count-2].ScriptName 
     $name = Split-Path -Path $fullPath -Leaf 
     $directory = Split-Path -Path $fullPath 
     $logDirectory = [IO.Path]::GetFullPath("$directory\..\scripts_logs") 
     md -force $logDirectory | out-null 
     $logFinalPath = "$logDirectory\$(Get-Date -Format o | foreach {$_ -replace ":", "."})_$name.log" 
     Set-Variable -scope 1 -name $TranscriptStartedPropertyName -value $True 
     Set-Variable -scope 1 -option private -name $TranscriptStartedPrivatePropertyName -value $True 
     Start-Transcript $logFinalPath | Write-Host 
    } 
    $immediateCallerPath = Get-Variable -scope 1 -name PSCommandPath -ValueOnly 
    Write-Host "Starting script at $immediateCallerPath" 
} 

function ConditionalStopTranscript 
{ 
    $immediateCallerPath = Get-Variable -scope 1 -name PSCommandPath -ValueOnly 
    Write-Host "Stopping script at $immediateCallerPath" 
    $transcriptStartedByMe = [bool](Get-Variable -scope 1 -name $TranscriptStartedPrivatePropertyName -ErrorAction Ignore) 
    if ($transcriptStartedByMe) 
    { 
     Stop-Transcript | Write-Host 
    } 
}