从单个父ps脚本调用的多个sub ps脚本记录输出的最佳简单方法是什么?

时间:2019-04-23 03:52:30

标签: powershell

1。任何好的做法和简单的方法来输出文本文件作为日志目的,以记录多个sub ps脚本操作,例如单父ps脚本中有3到10个部分? 需要记录对子ps脚本的父调用以及从子脚本的日志,以防发生任何异常情况。 是否有任何类似于linux sh脚本的管道函数,我可以将每个子脚本的输出附加到按日期生成的日志文件20190423 24 25 ...

#parent scripts

# sub 1
& '.\part1.ps1' # is there anything like writesth.ps1 | log_todayYYYYMMDD.txt ? forgive bringing some pipe concept from sh to ps but is it possible?
# sub 2
& '.\part2.ps1'
...
# sub scripts 10
& '.\part10.ps1'

2。如何制作通用日志功能以使每个位置的日志保持相同格式?

请尽可能提供一些样品。谢谢。

1 个答案:

答案 0 :(得分:0)

一段时间以来,我一直在重复使用此模块文件以将日志创建为CSV文件, 您可以仅将此代码保存为模块文件,可能是“ Powershell.Common.Logging.psm1”,然后在需要时导入(在主脚本中)Import-Module -Name "$PSScriptRoot\Modules\Powershell.Common.Logging.psm1" -Force

# -----------------------------------------------------------------------------
# Script: Common Logging
# Version: 1
# Modified By: Akhilesh Verma;
# Created Date: 1/4/2019
# Comments: Module to enable logging in powershell solution
# -----------------------------------------------------------------------------
$LogDirectoryPath = "$PSScriptRoot\..\Log\"
$global:LogFileName = $null
Set-Variable -Name LogSrc -Value "Main Module Name" -Scope Global -Force
Set-Variable -Name LogSrcCommon -Value "COMMON" -Scope Global -Force
Set-Variable -Name LogLvlERR -Value "ERROR" -Scope Global -Force
Set-Variable -Name LogLvlWRN -Value "WARNING" -Scope Global -Force
Set-Variable -Name LogLvlSUC -Value "SUCCESS" -Scope Global -Force
Set-Variable -Name LogLvlINF -Value "INFORMATION" -Scope Global -Force
Set-Variable -Name LogLvlVRB -Value "VERBOSE" -Scope Global -Force
Set-Variable -Name LogOpTRK -Value "TRACK" -Scope Global -Force
Set-Variable -Name LogOpRD -Value "READ" -Scope Global -Force
Set-Variable -Name LogOpWT -Value "WRITE" -Scope Global -Force
<#
.SYNOPSIS
Intialize the logging session by creating a new log file
.DESCRIPTION
Create Logfile and capture logging for the given Source  by creating a new log file
.PARAMETER InputPath
-Source $LogSrcReconciliation
.PARAMETER OutputPath
None.
.INPUTS
None. You cannot pipe objects.
.OUTPUTS
None. The function generate a log file in the log folder
.EXAMPLE
Start-Logging -Source $LogSrcReconciliation
#>
function Start-Logging{
Param(
    [Parameter(Mandatory=$true)]
    [ValidateNotNullOrEmpty()]
    [string]$Source
)
#ensure log directory exists
if (!(Test-Path $LogDirectoryPath)) {
    New-Item $LogDirectoryPath -ItemType Directory -Force | Out-Null
}
$newLogPath = 'Powershell.Log_' + ((Get-Date).tostring("yyyyMMdd_HHmmss")) + '.csv'
Set-Variable -Name 'LogFileName' -Value $newLogPath -Scope Global
$LogFilePath = Join-Path $LogDirectoryPath -ChildPath $global:LogFileName
$FormattedDate = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
# Write log entry to $Path
$row = New-Object System.Object # Create an object to append to the array
$row | Add-Member -MemberType NoteProperty -Name "Date & Time" -Value $FormattedDate
$row | Add-Member -MemberType NoteProperty -Name "Source" -Value $Source
$row | Add-Member -MemberType NoteProperty -Name "Operation" -Value $LogOpTRK
$row | Add-Member -MemberType NoteProperty -Name "Level" -Value $LogLvlVRB
$row | Add-Member -MemberType NoteProperty -Name "Reference" -Value 'Start-Logging'
$row | Add-Member -MemberType NoteProperty -Name "Message" -Value 'Logging Started.'
$row | Add-Member -MemberType NoteProperty -Name "Path/URL" -Value $LogFilePath
$row | Add-Member -MemberType NoteProperty -Name "Function ID" -Value '00000000-0000-0000-0000-000000000000'
$row | Export-Csv -Path $LogFilePath -Append -Force -NoTypeInformation
}

<#
.SYNOPSIS
Write Message to host and log file.
.DESCRIPTION
Intialize the logging session by creating a new log file
.PARAMETER InputPath
-Message - Message to log
-Source - Source of the call, Migration/SharePoint/Sharegate
-Level - Logging level, ERROR/WARNING/INFO/SUCCESS.
-Operation - Releated Operation, Read/Write/Track
-Reference - File system Path or SharePoint URL to track log origin
.PARAMETER OutputPath
None.
.INPUTS
None. You cannot pipe objects.
.OUTPUTS
None. The function generate a log file in the specified folder
.EXAMPLE
Write-Log   $ScriptStackTrace -Level 'Error' -Operation 'Read' -Source     $LogSrcMigration
#>
function Write-Log{
[CmdletBinding()]
Param(
    [Parameter(Mandatory=$true, ValueFromPipelineByPropertyName=$true)]
    [ValidateNotNullOrEmpty()]
    [string]$Message,
    [Parameter(Mandatory=$true)]
    [ValidateNotNullOrEmpty()]
    [string]$Source,
    [Parameter(Mandatory=$false)]
    [ValidateSet("ERROR", "WARNING", "SUCCESS", "INFORMATION", "VERBOSE")]
    [string]$Level=$LogLvlINF,
    [Parameter(Mandatory=$false)]
    [ValidateSet("TRACK", "WRITE", "READ")]
    [string]$Operation= $LogOpTRK,
    [Parameter(Mandatory=$false)]
    [string]$Reference='N/A',
    [Parameter(Mandatory=$false)]
    [guid]$FunctionId = '00000000-0000-0000-0000-000000000000',
    [Parameter(Mandatory=$false)]
    [string]$Path = '',
    [Parameter(Mandatory=$false)]
    [switch]$RemoteLogging = $false
)
Process{
    # Format Date for our Log File
    $FormattedDate = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
    # Write message to output and set the $LevelText
    $completeMsg = $FormattedDate + " | " + ("{0, -12}" -f $Level) + ": $Message $Path"
    switch ($Level) {
        $LogLvlERR {
            Write-Host $completeMsg -f Red
        }
        $LogLvlWRN {
            Write-Host $completeMsg -f Cyan
        }
        $LogLvlINF {
            Write-Host $completeMsg -f Yellow
        }
        $LogLvlSUC {
            Write-Host $completeMsg -f Green
        }
        $LogLvlVRB {
            Write-Host $completeMsg -f White
        }
    }
    if($RemoteLogging){
        Send-RemoteLog -Message $Message -Source $Source -Level $Level -Operation $Operation `
         -Reference $Reference -Path $Path -FunctionId $FunctionId
    }
    $LogFilePath = Join-Path $LogDirectoryPath -ChildPath $LogFileName
    # Write log entry to $Path
    $row = New-Object System.Object # Create an object to append to the array
    $row | Add-Member -MemberType NoteProperty -Name "Date & Time" -Value $FormattedDate
    $row | Add-Member -MemberType NoteProperty -Name "Source" -Value $Source
    $row | Add-Member -MemberType NoteProperty -Name "Operation" -Value $Operation
    $row | Add-Member -MemberType NoteProperty -Name "Level" -Value $Level
    $row | Add-Member -MemberType NoteProperty -Name "Reference" -Value $Reference
    $row | Add-Member -MemberType NoteProperty -Name "Message" -Value $Message
    $row | Add-Member -MemberType NoteProperty -Name "Path/URL" -Value $Path
    $row | Add-Member -MemberType NoteProperty -Name "Function ID" -Value $FunctionId
    $row | Export-Csv -Path $LogFilePath -Append
}
}

然后您只需要初始化     

Start-Logging -Source $LogSrc
并开始记录-     
Write-Log "Message you want to log" -Level $LogLvlINF -Operation $LogOpTRK -Path "path related to operation" -Reference $MyInvocation.MyCommand -Source $LogSrc -FunctionId $FunctionId
您还可以为每个操作生成一个GUID,并使用FunctionID参数

跟踪各个函数的调用