Friday, June 19, 2020

PowerShell using more effective & efficient intelligent coding;

PowerShell using more effective & efficient intelligent coding;

Over many years I have learned tons, what and what not to do when it comes to writing PowerShell scripts. I am still eagerly learning each day and putting work to improve skill set. With this article I will be sharing some of the basic work flow and rules do think each scripter should follow to improve the quality of their work. Let’s jump right into it.

  • Be organized, make sure your code is readable. 
  • Use Synopsis , explain in a good format, what your script does
  • Make sufficient notes to pass on your thought process to next person who is reading your code.
  • Use consistent format 
  • Use functions when you can 

Few examples added below to help you to tune up your work and present it much better way. Pay attention how functions are being used to follow simple format and how to organize your scripts and log files.

<#    
  
 
.NOTES
#=============================================
# Script      : Generate-AD-HomeDirectory-Size-Report-V2.ps1
# Created     : ISE 3.0 
# Author(s)   : CA-Casey.Dedeal 
# Date        : 04/07/2020 09:24:18 
# Org         : ETC Solutions
# File Name   : GenerateReport-V2.ps1
# Comments    : AD reports Users Home Drive
# Assumptions : Running as an Administrator in Domain environment
#==============================================
 
SYNOPSIS           : Generate-AD-HomeDirectory-Size-Report-V2.ps1
DESCRIPTION        : Gathering AD users home drive sizes
Acknowledgements   : Open license
Limitations        : None
Known issues       : None
Credits            : None
 
.EXAMPLE
  .\Generate-AD-HomeDirectory-Size-Report-V2.ps1
 
  MAP:
  -----------
  #(1)_.Log and export CSV vars
  #(2)_.Run report folder function
  #(3)_.Start transcript, to provide intensive logging
  #(4)_.Function-Archive-Reports
  #(5)_.Run Function to get CSV file -GUI lets admins locate the CSV fil
  #(6)_.Start reading CSV file now import into a variable
  #(7)_.Check CSV header to make sure correct header is specified on the imported CSV file
  #(8)_.Function load AD module
  #(9)_.Function AD user Home drive Information
  #(10)_.Add log Function to capture script logs
  #(11)_.Function for getting current time
  #(12)_.Adding counter and calculating total users, providing info to enter the loop
  #(13)_.Set counter
  #(14)_.Enter into loop start processing scanning
  #(14.1)_.Show progress current user
  #(14.2)_.Run Function-Get-ADusers-Report
  #(14.3).Catch errors , write to log file
  #(15)_.Open report folder
  #(16)_.Stop Transcript
  #(17)_.Run Function-Archive-Reports
  #(18)_.Option to open reports folder
 
 
 
#> 
 


 

#(1)_.Create Log folder vars
 $repname = 'REPORTNAME-REPORT'
 $logout  = $repname+'-Log.TXT'
 $csvout  = $repname+'-Log.CSV'
 $repout  = $repname+'-DETAILED.CSV'
 $traout  = $repname+'-Transcript.LOG'
 $logTXT  = $desFol+$now+$logout
 $logCSV  = $desFol+$now+$csvout
 $repCSV  = $desFol+$now+$repout
 $scrTXT  = $desFol+$now+$traout
 $luser   = $env:USERNAME
 $desFol  = "C:\temp\Reports_\$repname\"
 
 

 #(2)_.Run report folder function

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
 
 
 
 

 

 
#(3)_.Archive logs
 
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')
     $messageTO = 'Casey.DeDeal@associates.tsa.dhs.gov'
     }
 
     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'
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'
Zip'
         Write-Host 'Script will stop'
stop'
         Start-Sleep
-Seconds 5
         break;
           }
 
        write-host "Total files located:"
files located:" $total -ForegroundColor White
        write-host "Moving files into ZIP Folder:"
files into ZIP Folder:" -ForegroundColor
White
        $list | move-Item -Destination
$ArcFol
        write-Host "Zipping Archive folder"
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 "Zip folder exist"
folder exist" -ForegroundColor Green
    write-Host "Completed"
 
         }
 
       }Catch{
         $errofile =
$($PSItem.ToString())
         write-Warning 'Error has occoured'
has occoured'
         write-host 'Problem FOUND'
FOUND' $errofile -ForegroundColor red
-BackgroundColor Black
         Write-Log -Message $errofile -Severity
Error
          }
     }
 
     End {
 
     }
 
}
 

 

 

 
#(4)_.Start transcript
Start-Transcript -Path $scrTXT -Append | Out-Null
 

 

 

 

#(5)_.Script goes here
 
  Try{
 
  # < CODE GOES HERE >
 
 
 
  }Catch{
 
  $errofile = $($PSItem.ToString())
  Write-Warning 'Error has occoured'
  Write-host 'Problem FOUND' $errofile -ForegroundColor red -BackgroundColor Black
 
  }
 

 

 
#(6)_.Open report folder
write-host $null
Write-host 'Completed:' $repname -ForegroundColor DarkYellow
 
#(7)_.Stop Transcript
Write-host 'Stopping transcript' -ForegroundColor White
Stop-Transcript | Out-Null
Start-Sleep -Seconds 10
 
#(8)_.Run Function-Archive-Reports
Write-host 'Archiving logs' -ForegroundColor White
Function-Archive-Reports -repName $Repname -source $desFol
Write-host 'Completed' -ForegroundColor White
 
#(9)_.Option to open reports folder
Read-host 'Press <ENTER> to open reports folder'
start $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


No comments:

Post a Comment