Powershell在模块和点源脚本中记录

时间:2017-10-19 15:54:58

标签: powershell logging

我有几个函数存储在.psm1文件中,由几个不同的ps1脚本使用。我创建了一个日志记录功能(如下所示),我在这些ps1脚本中使用它。通常,我通过简单地调用类似的东西在脚本中导入模块:

df[df.location == 'a1']
  location description price qty
0       a1          b1    c1  d1

然后在模块中,我有一个写入记录器功能:

Import-Module $PSScriptRoot\Module_Name.psm1

此功能在整个主脚本和模块本身中使用。 splatting参数Write-Logger -Message "Insert log message here." @logParams 在我的主.ps1文件中定义,并没有显式传递给模块,我想这些变量在导入时隐含在模块的范围内。我有什么作品,但我觉得这不是一个很好的做法。是否更好的做法是在我的模块中添加@logParams块以要求从主.ps1脚本显式传递param?谢谢!

@logParams

1 个答案:

答案 0 :(得分:0)

我在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' )

}