Create Log File in Powershell

前端 未结 8 2129
半阙折子戏
半阙折子戏 2020-11-30 22:11

I have the below code and currently it loads all the information on screen. I want it to log to a log file on D:\\Apps\\Logs.

The log file needs to have the name of

8条回答
  •  旧巷少年郎
    2020-11-30 22:42

    A function that takes these principles a little further.

    1. Add's timestamps - can't have a log without timestamps.
    2. Add's a level (uses INFO by default) meaning you can highlight big issues.
    3. Allows for optional console output. If you don't set a log destination, it simply pumps it out.

      Function Write-Log {
          [CmdletBinding()]
          Param(
          [Parameter(Mandatory=$False)]
          [ValidateSet("INFO","WARN","ERROR","FATAL","DEBUG")]
          [String]
          $Level = "INFO",
      
          [Parameter(Mandatory=$True)]
          [string]
          $Message,
      
          [Parameter(Mandatory=$False)]
          [string]
          $logfile
          )
      
          $Stamp = (Get-Date).toString("yyyy/MM/dd HH:mm:ss")
          $Line = "$Stamp $Level $Message"
          If($logfile) {
              Add-Content $logfile -Value $Line
          }
          Else {
              Write-Output $Line
          }
      }
      

提交回复
热议问题