Wednesday, June 10, 2020

Function to Zip log files


Below Functions will help you to organize your scripts. First function will create reporting folder to store all script related reports. Second function will zip files within report folder and archive them. When zipping files it will put a time stamp and if there is no file to zip it will stop. I have built a filter to collect desired file types, which can easily be modified if desired. Keep scripting and stay organized.

 Function-Check-Report-Folder

 
 
#(1)_.Create Log folder vars
$Repname  = 'MYREPORT-Report'
$logname  = $Repname+'-Log.TXT'
$csvname  = $Repname+'-Log.CSV'
$traname  = $Repname+'-Transcript.LOG'
$now      = (get-Date -format 'dd-MMM-yyyy-HH-mm')
$user     = $env:USERNAME
$desFol   = ("C:\temp\$Repname\")
$logfile  = $desFol+$now+$logname
$csvfile  = $desFol+$now+$csvname
$scrfile  = $desFol+$now+$traname
 
function Function-Check-Report-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-Check-Report-Folder -DestinationFolder $desFol
 
 
 

 




function Function-Archive-Reports

 

function Function-Archive-Reports {
[cmdletbinding()]
param(
     [parameter(
         Mandatory=$true)]
         [String]$repName,
         [String]$source
)
 
     Begin
{
        
    # Add Vars
     $now     =
(Get-Date -format 'dd-MMM-yy-HH-mm-ss')
     $folName = ($now+$repname)+'.Archive'
     $ArcFol  =
($desFol)+$folName
     $zipFolder = ($ArcFol+'.zip')
 
     }
 
     Process
{
     # Check Archive Folder create if it does not exist
     If
(!( Test-Path $ArcFol )) {
               New-Item -ItemType Directory -Force $ArcFol | Out-Null
         }
 
      Try{
 
       # Get List
       write-Host 'Moving files into archive folder' -ForegroundColor DarkYellow
        $list = get-childItem $desFol | `
                   ?{$_.Extension -like '.CSV' -or $_.Extension -like '.LOG'}
        #Count Items for invetory                   
        $total = ($list).count
        if
($total -like '0'){
         Write-Host 'Nothing to Zip'
         Write-Host 'Script will stop'
         Start-Sleep -Seconds 5
         break;
           }
 
        write-host "`tTotal files located:" $total -ForegroundColor White
        write-host "`tMoving files into ZIP Folder:" -ForegroundColor White
        $list | move-Item -Destination $ArcFol
        write-Host "`tZipping Archive folder" -ForegroundColor White
 
    If
(!( Test-Path $zipFolder )) {
  
      Add-Type -assembly 'system.io.compression.filesystem' -ErrorAction Stop
     [io.compression.zipfile]::CreateFromDirectory($ArcFol, $zipFolder)
 
    }else{
    Write-Host "`tZip folder exist" -ForegroundColor Green
    write-Host "`tCompleted"
 
         }
 
       }Catch{
         $errofile = $($PSItem.ToString())
         write-Warning 'Error has occoured'
has occoured'
         write-host 'Problem FOUND' $errofile -ForegroundColor red -BackgroundColor Black
          }
     }
 
     End
{
 
     }
 
}
 
Function-Archive-Reports -repName $Repname -source $desFol
 

 

 

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



 


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

Monday, June 1, 2020

Validate CSV File headers;


Below example will provide quick snippets to provide validation on the CSV headers to make sure expected header within selected CSV file is provided. If expected CSV header is not found, script will stop.

First function is to select CSV file and import it

#(1)_.Run Function to get CSV file -GUI lets administrators locate the CSV file

 

Function Import-CSVfile($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)_.Import CSV file

 

$csvfile     = Import-CSVfile -initialDirectory $inDir

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

 

 

 

#(3)_.Validate CSV Header value, expected header from CSV file is, in this example $header = 'sAMAccountName'

 

$varInf = 'sAMAccountName'

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

 

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

  Write-Host 'Script will STOP'

  Start-Sleep -Seconds 5

  break;

 

}

 

 

#(4)_.Same task, Validate CSV header stop script if expected header is not found

 

 

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

$varInf = 'sAMAccountName'

 

if ($header -like  $varInf ){

 

Write-Host 'Header has correct value' -ForegroundColor Green

 

}else{

 

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

 

}

 

 

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