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


Monday, December 28, 2020

Merge CSV files by using PowerShell

 

Compare two CSV files via PowerShell to find out difference and export results into new CSV file.

If you are looking for simple script can read two CSV file, which each CSV file has multiple columns, then compare them to find out the difference this script is just going to do that. Simply download and adjust few variables to make it work for your scenario.

I have added both CSV file content into script for you to see what script is pulling then variables you can change to make it fit into your needs.

Adjust your CSV file, if your columns are different, you have more columns etc. that is fine, just adjust them accordingly.

“Computername, and UserName “ are column name on the example below, thus script reflect both variables, and also PS custom object, just adjust them.

 

<#

 

#$File1

 

ComputerName UserName

------------ --------

XLT-001      Allison1

XLT-002      Allison2

XLT-003      Allison3

XLT-004      Allison4

XLT-005      Allison5

XLT-006      Allison6

XLT-007      Allison7

XLT-008      Allison8

XLT-009      Allison9

XLT-010      Allison10

WRK-010      Clint

 

#$File2

ComputerName UserName

------------ --------

XLT-001      Allison1

XLT-002      Allison2

XLT-003      Allison3

XLT-004      Allison4

XLT-005      Allison5

XLT-006      Allison6

XLT-007      Allison7

WRK-001      RAMBO   

XLT-008      Allison8

XLT-009      Allison9

XLT-010      Allison10

 

 

#>

 

 

 

#(1)_.Path for CSV Files that needs to be comppared

$CSV1 = "C:\Users\12024\OneDrive - wiretecpro\Desktop\Compare-CSV\Excell\File1.csv"

$CSV2 = "C:\Users\12024\OneDrive - wiretecpro\Desktop\Compare-CSV\Excell\File2.csv"

 

 

 

#(2)_.Path for export results to CSV

$CSV3 = "C:\Users\12024\OneDrive - wiretecpro\Desktop\Compare-CSV\Excell\DIFFERENCE.csv"

 

 

 

#(3)_.Import both CSV Files you would like to compare

$File1 = Import-Csv $CSV1

$File2 = Import-Csv $CSV2

 

 

#(4)_.Compare both CSV files - column ComputerName,UserName

 

$Results = Compare-Object  $File1 $File2 -Property ComputerName,UserName -IncludeEqual

 

 #(5)_.Set Array

$Array = @()

 

#(6)_.Loop Starts     

Foreach($item in $Results)

{

    If( $item.sideindicator -notcontains "==" )

    {

        $Object = [pscustomobject][ordered] @{

            ComputerName      = $item.ComputerName

            UserName          = $item.UserName

            Compare_Indicator = $item.sideindicator

 

        }

        $Array += $Object

    }

}

 

#(7)_.Count users in both files

($Array | sort-object ComputerName | Select-Object * -Unique).count

 

#(8)_.Display results in console

$Array

 

#(9)_.Export results into CSV File

$Array | export-csv -Path $CSV3 -NoTypeInformation

 

 

Casey, Dedeal

Principal Systems Engineer

https://simplepowershell.blogspot.com/  (blog)

https://smtp25.blogspot.com/ (blog)

https://telnet25.wordpress.com/ (blog)

https://twitter.com/Message_Talk (Twitter)

Setting up ISE Profile with Options

  Here is updated ISE profile. You can use it to built your own and make few adjustments.       # STARTING ADDS-ON MENU # ...