guyrleech

Create log file with date elements in path

Apr 28th, 2022 (edited)
698
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. ## $logFile passed as a parameter such as "%systemdrive%\%year%\%monthname%\blah-%hour%.%minute%-%day%.%month%.%year%.log"
  2. ## $appendToLogfile is a [switch] parameter to determine if log file is appended to or overwritten (default)
  3.  
  4. if( -Not [string]::IsNullOrEmpty( $logFile ) )
  5. {
  6.     ## allow place holders for date elements
  7.     [datetime]$now = [datetime]::Now
  8.     [string]$actualLogFile = [System.Environment]::ExpandEnvironmentVariables( $logFile ) -replace '%year%' , $now.Year -replace '%monthname%' , ((Get-Culture).DateTimeFormat.GetMonthName( $now.Month )) -replace '%month%' , ( '{0:D2}' -f $now.Month ) `
  9.                                 -replace '%day%' , ( '{0:D2}' -f $now.Day ) -replace '%dayname%' , ((Get-Culture).DateTimeFormat.GetDayName( $now.Month )) -replace '%hour%' , ( '{0:D2}' -f $now.Hour ) -replace '%minute%' , ( '{0:D2}' -f $now.Minute ) `
  10.                                     -replace '%second%' , ( '{0:D2}' -f $now.Second )
  11.     [string]$logFolder = Split-Path -Path $actualLogFile -Parent
  12.     if( -Not ( Test-Path -Path $logFolder ) )
  13.     {
  14.         if( -Not ( New-Item -Path $logFolder -ItemType Directory -Force ) )
  15.         {
  16.             Write-Warning -Message "Failed to create log file folder `"$logFolder`""
  17.         }
  18.     }
  19.     Write-Verbose -Message "Log file is `"$actualLogFile`""
  20.  
  21.     Start-Transcript -Path $actualLogFile -Append:$appendToLogfile
  22. }
Add Comment
Please, Sign In to add comment