Monday, June 8, 2020

Check CSV Headers to make sure if expected CSV value is provided from selected CSV file


Check CSV Headers to make sure if expected CSV value is provided from selected CSV file

I am sharing two functions, which are extremely useful for your scripts. First function will use Dialog box and ask administrator to pick the import file, it will then load into selected variable.

Second Function will check expected CSV header to ensure desired header value is there.

# Select File to Import

 

 

#(1)_.Open GUI to locate import file

Function Get-File($inDir)

 

 [System.Reflection.Assembly]::LoadWithPartialName('System.windows.forms'| Out-Null

 $OpenFileDialog = New-Object System.Windows.Forms.OpenFileDialog

 $OpenFileDialog.initialDirectory = $inDir

 $OpenFileDialog.filter = 'All files (*.*)| *.*'

 $OpenFileDialog.ShowDialog() | Out-Null

 $OpenFileDialog.filename

 $inDir = 'C:\temp\Migration_CSV_Files\'

}

 

 

#(2)_.Start reading selected file , load collected data into $variable

 $csvfile   = Get-File -initialDirectory $inDir

 $UserList  = Import-Csv -path $csvfile -ErrorAction Stop

 

 

 

 

 

#(3)_.Function to check header information

 function Function-Check-Header {

 [cmdletbinding()]

 param(

     [parameter(

         Mandatory=$true)]

         [String]$CSVheader

 )

 

     Begin {

 

        #(-)_.Set var for header

         $header = $UserList[0].psobject.Properties.Name

     }

 

     Process {

        

    #(-)_.Validate CSV Header value

    if (!($header -like $CSVheader) ){

 

    Write-Host 'Header DOES NOT have correct value'-ForegroundColor Red -BackgroundColor White

    Write-Host "`t(1)_.Expected CSV header <value>:"$CSVheader -ForegroundColor DarkYellow

 }

 

     }

 

     End {

 

         write-Host "`t(2)_.Script will STOP" -ForegroundColor DarkYellow

         write-Host "`t(3)_.Select correct file" -ForegroundColor DarkYellow

         Start-Sleep -Seconds 5

         break;

     }

 

 }

 


# Usage 
Function-Check-Header -CSVheader 'SamAccountName'  

Azure Solutions Architect

AWS Certified Cloud Practitioner

Azure Certified Security Engineer Associate

https://simplepowershell.blogspot.com

https://cloudsec365.blogspot.com

https://msazure365.blogspot.com

https://twitter.com/Message_Talk

No comments:

Post a Comment