Advertisement
Sekers

Sample PowerShell Compare-Object

Apr 9th, 2020
893
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1.     #Verify backup file exists
  2.     If(-not (Test-Path $outputpath))
  3.     {
  4.         $CustomErrorMessage = "Error creating backup file at " + $outputpath + "`n`n" + "Verify backup path is correct, backup location is available, and that your account has write permission."
  5.         Write-Host $CustomErrorMessage
  6.         EmailError($CustomErrorMessage)
  7.         Continue #Exits the ForEach loop
  8.     }
  9.  
  10.     #Compare Downloaded File to last existing backup and only keep if different (so you don't have a hundred copies of the same file)
  11.     #Get latest file (excluding the one just downloaded)
  12.     $lastbackupfile = $(Get-ChildItem -Path $outputfolder | Sort-Object LastWriteTime -Descending | Select-Object -Index 1)
  13.     $lastbackupfilepath = $outputfolder + $lastbackupfile
  14.     Try
  15.     {
  16.         If($null -ne $lastbackupfile) #make sure that there actually is an existing backup to compare to
  17.         {
  18.             if(-NOT(Compare-Object -ReferenceObject $(Get-Content $outputpath) -DifferenceObject $(Get-Content $lastbackupfilepath)))
  19.             {
  20.                 #Files are the same; no need to keep backup
  21.                 Remove-Item -Path $outputpath
  22.                 Write-Host("No Changes to Configuration for Switch " + $line.hostname + ".")
  23.             }
  24.             Else
  25.             {
  26.                 #Files are different; keep latest backup
  27.                 Write-Host New Backup File Created: $outputpath
  28.             }
  29.         }
  30.         else
  31.         {
  32.             #If no previous backup file; keep latest backup
  33.             Write-Host New Backup File Created: $outputpath
  34.         }
  35.     }
  36.     Catch
  37.     {
  38.         $CustomErrorMessage = "Error Comparing previous config for switch " + $line.hostname + "`n`n" + "Error Message is: " + $_.Exception.Message + "`n`n" + "If the object is null it may be you have an empty file in the directory."
  39.         Write-Host $CustomErrorMessage
  40.         EmailError($CustomErrorMessage)
  41.         Continue #Exits the ForEach loop
  42.     }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement