TEXT

Sunday, January 3, 2021

PowerShell scripting, writing to logs then extracting progress information.

PowerShell scripting, writing to logs then extracting progress information.

If you are writing PowerShell scripts, you will understand and appreciate the ability to get log information from your scrips. Below function called “Write-Log-Advance” is just going to do that for you.

You can modify it as you wish to make it fit into your needs or use it the way it is.  What I have here for you is, function to create log folder and all VARs goes with it. On the bottom, there is try & Catch simple code to show you how to capture errors within your scripts. One thing I would highly recommend, is to work organized. Label all your VARs and provide summary information for each section of the script.

Also using variables then passing it to  write-host and write-log-Advance one at the time, is much smart way of fulfilling multiple tasks in my opinion. Following my logic you can expand and integrate logging within your scripts.

Happy Scripting.

#(1)_.Create Log folder vars

$repname = Read-host 'Provide Report Name'

 IF(!($repname)){

 $repname = 'DEFAULT-REPORT'}

 $logout  = $repname+'-Log.TXT'

 $csvout  = $repname+'-Log.CSV'

 $repout  = $repname+'-Advance-Log.CSV'

 $traout  = $repname+'-Transcript.LOG'

 

 $logTXT  = $desFol+$now+$logout

 $logCSV  = $desFol+$now+$csvout

 $AdvCSV  = $desFol+$now+$repout

 $scrTXT  = $desFol+$now+$traout

 $luser   = $env:USERNAME

 $desFol  = "C:\temp\Reports_\$repname\"

 

#(2)_.Function to create log folder

 

function Function-Create-Log-Folder{

 

  [CmdletBinding()]

  param(

  [Parameter(Mandatory=$True)]

  [String]$DestinationFolder

 

  ) 

 

  Try{

 

  If (!(Test-Path $DestinationFolder)){

     New-Item -ItemType Directory -Force $DestinationFolder | Out-Null

     }

  }Catch{

 

  $errofile = $($PSItem.ToString())

  Write-Warning 'Error has occoured'

  Write-host 'Problem FOUND' $errofile -ForegroundColor red -BackgroundColor Black

 

    }

 

}

Function-Create-Log-Folder -DestinationFolder $desFol

 

#(3)_.running Advance Write Log Function

function Write-Log-Advance {

     [CmdletBinding()]

     param(

         [Parameter()]

         [ValidateNotNullOrEmpty()]

         [string]$Count,

         [string]$Message1,

         [string]$Message2,

         [string]$Message3,

         [string]$Message4,

         [string]$Message5,

         [string]$Info1,

         [string]$Info2,

         [string]$Info3,

         [string]$Info4,

         [string]$Error1,

         [string]$Error2

     )

 

     $now = (Get-Date).ToString('MM-dd-yyyy-hh-mm-ss-tt')

     [pscustomobject]@{

        

         Count     = $Count

         Message1  = $Message1

         Message2  = $Message2

         Message3  = $Message3

         Message4  = $Message4

         Message5  = $Message5

         Info1     = $Info1

         Info2     = $Info2

         Info3     = $Info3

         Info4     = $Info4

         Error1    = $Error1

         Error2    = $Error2

         Time      = (Get-Date -f g)

 

     } | Export-Csv -Path $AdvCSV -Append -NoTypeInformation

 }

 

 

 

 

 

Testing out logging on your own.

 

#(4)_.Adding VARS

 $total     = 20

 $i         = 1

 $remaining = $total-$i

#(5)_.While Loop

while($i -lt $total)

{

 

  #(-)_.VARS and Messages

    $remaining = $total-$i

    $user = 'John.Doo'

    $message1 = "Processing $user "

    $message2 = "Server:MBX($i)"

    $message3 = "Completed work"

    $Info1 = "Total Users:$total, Completed:$i, Remaining:$remaining"

    $info2 = "$user migration completed"

    Write-Progress $message1 $message4

    Write-host "Processing $user($i)"

 

    #Write-Log

    Write-Log-Advance -Count ($i-Message1 $message1 -Message2 $message2 `

                      -Message3 $message3 -Info1 $Info1

    $i++

}

 

# Reading Logs for progress and exporting them

#(6)_.Import CSV Log Files

$Info1 = (Import-Csv $CSVImportPath).Info1

 

#(7)_.Extracting specific info then export into CSV

$ReportInfo = $Info1

$ReportInfo | Select-Object -Last 1

 

#(8)_.Export CSV

$ReportInfo | foreach {[PSCustomObject] @{Items = $_}} | `

           Export-Csv -Path $LogExportPath

 

 

How to capture Errors

 

Try{

   

  # <Insert your code HERE> -ErrorAction Stop

  # Get-Service -Name RAMBO -ErrorAction Stop

 

}Catch{

  $errormessage1 = $($PSItem.ToString())

  $ErrorMessage2 = $($_.Exception.Message)

 

  Write-Warning 'ERROR HAS OCCURED'

  Write-host 'PROBLEM FOUND:' $errormessage1 -ForegroundColor Red -BackgroundColor White

  Write-host 'PROBLEM FOUND:' $errormessage2 -ForegroundColor Red -BackgroundColor White

  Write-Log-Advance -Error1 $errormessage1 -Error2 $errormessage2

 

      }

 

Casey, Dedeal

Azure Solutions Architect

AWS Certified Cloud Practitioner

https://simplepowershell.blogspot.com

https://cloudsec365.blogspot.com

https://msazure365.blogspot.com

https://twitter.com/Message_Talk


No comments:

Post a Comment

Simple Function Do Something

   Use template below to create simple PS function    # Simple Function Do Something # Change $ReportName   function Fu...