Tuesday, June 23, 2020

PowerShell using RoboCopy, Copy Folders/Content to another location;

PowerShell using RoboCopy, Copy Folders/Content to another location;

There are several options when it comes to copy files from source to destination directory. You can use native PowerShell cmdlet “copy-item” however, you will quickly realize it is super slow. Using RoboCopy is the way to go by and here is simple and effective script to get the job done.


<#    
  
 
.NOTES
#=============================================
# Script      : RoboCopy-Files-V1.ps1
# Created     : ISE 3.0 
# Author(s)   : CA-Casey.Dedeal 
# Date        : 06/23/2020 12:58:36 
# Org         : ETC Solutions
# File Name   : RoboCopy-Files-V1.ps1
# Comments    : Copy Files from source to destination
# Assumptions :
#==============================================
 
SYNOPSIS           : RoboCopy-Files-V1.ps1
DESCRIPTION        : Copy folders/content source to destination
Acknowledgements   : Open license
Limitations        : None
Known issues       : None
Credits            : None
 
.EXAMPLE
  .\RoboCopy-Files-V1.ps1
 
  MAP:
  -----------
  #(1)_.Adding Vars
  #(2)_.Define source and destination vars
  #(3)_RoboCopy Options
  #(4)_.Function to check/create destination folder
 
  Note : Take out /TEE option if you want silent mode
  $Options     = ("/B","/MIR", "/XJ", "/FFT", "/R:0", "/V", "/LOG:$LogFile")
 
#>
 
 
 
#(1)_.Define source and destination vars
$timestamp = (Get-Date -format 'dd-MMM-yyyy-HH-mm-ss-')
$fileName  = 'RoboCopy.LOG'
$logname   = $now+$Filename
 
#(2)_RoboCpy Options
$dataSource  = ("\\kckvdts107\c$\Users\$luser\Documents\S_Drive_Scripts_\PS_Scripts\")
$dataDestin  = ("\\kckvdts109\c$\Users\$luser\Documents\S_Drive_Scripts_\")
$LogFile     = ($dataDestin+$logname )
$Options     = ("/B","/MIR", '/TEE', "/XJ", "/FFT", "/R:0", "/V", "/LOG:$LogFile")
 
 
#(3)_.Function to check/create destination folder
Function Function-Check-Destination-Folder{
 
  [CmdletBinding()]
  param(
    [parameter(
     Mandatory         = $true,
     ValueFromPipeline = $true)]
      [string]$DestinationPath)
 
 Try{
 
 if (!(Test-Path -Path $DestinationPath))
 {
  New-Item -Type Directory -Path $DestinationPath -ErrorAction Stop | Out-Null
 }
 
}catch{
  
    $errormessage = $($PSItem.ToString())
    Write-Warning 'Error has occoured'
    Write-host 'Problem FOUND:' $errormessage -ForegroundColor Red -BackgroundColor Black
   }
}
 
#(4)_.Function-Check-Source Folder , Stop if not found
Function Function-Check-Source-Folder{
 
  [CmdletBinding()]
  param(
    [parameter(
     Mandatory         = $true,
     ValueFromPipeline = $true)]
      [string]$SourcePath)
 
 Try{
 
 if (!(Test-Path -Path $SourcePath))
 {
     Write-Host 'CANNOT locate (SOURCE) directory' -ForegroundColor White -BackgroundColor Red
     Write-Host 'Script will stop' -ForegroundColor Yellow
     break;
 
 }
 
}catch{
  
    $errormessage = $($PSItem.ToString())
    Write-Warning 'Error has occoured'
    Write-host 'Problem FOUND:' $errormessage -ForegroundColor Red -BackgroundColor Black
   }
}
 
#(5)_.Check source path,Action:<STOP>, if it does not exist
Function-Check-Source-Folder -SourcePath $dataSource
 
#(6)_.Create Destination,action:<CREATE>, if it does not exist
Function-Check-Destination-Folder -DestinationPath $dataDestin
 
#(7)_Start Robocopy with pre-defined options
 
write-host '++++++++++++++++++++++++++++++++++++++++++++++++++++'
Write-host 'Starting RoboCopy now' -ForegroundColor Green
robocopy $dataSource $dataDestin $Options 
 

 

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

 


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


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

Microsoft M365 F3 licensing Limitations and Confusion

If you are working in regulated environment you could be dealing with F3 license for some of your users and I am sure you have read MS licen...