Guest User

Untitled

a guest
Mar 25th, 2017
128
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. param(
  2.     $encrypted_path = "C:\PoShTest\Encrypted",
  3.     $decrypted_Path = "C:\PoShTest\Decrypted\",
  4.     $processed_Path = "C:\PoShTest\Processed\",
  5.     $password_Path  = "C:\PoShTest\Passwords\Passwords.txt"
  6. )
  7. $ErrorActionPreference = "SilentlyContinue"
  8.  
  9. # Get Current EXCEL Process ID's so they are not affected by the scripts cleanup
  10. $currentExcelProcessIDs = (Get-Process excel).Id
  11. $startTime = Get-Date
  12.  
  13. Clear-Host
  14.  
  15. $passwords = Get-Content -Path $password_Path
  16. $encryptedFiles = Get-ChildItem $encrypted_path
  17. [int] $count = $encryptedFiles.count - 1
  18. $ExcelObj = New-Object -ComObject Excel.Application
  19. $ExcelObj.Visible = $false
  20. $encryptedFiles | % {
  21.     $encryptedFile  = $_
  22.     Write-Host "Processing" $encryptedFile.name -ForegroundColor "DarkYellow"
  23.     Write-Host "Items remaining: " $count
  24.     if ($encryptedFile.Extension -like "*.xls*") {
  25.         $passwords | % {
  26.             $password = $_
  27.             # Attempt to open encryptedFile
  28.             $Workbook = $ExcelObj.Workbooks.Open($encryptedFile.fullname, 1, $false, 5, $password)
  29.             $Workbook.Activate()
  30.  
  31.             # if password is correct save decrypted encryptedFile to $decrypted_Path
  32.             if ($Workbook.Worksheets.count -ne 0 ) {
  33.                 $Workbook.Password = $null
  34.                 $savePath = Join-Path $decrypted_Path $encryptedFile.Name
  35.                 Write-Host "Decrypted: " $encryptedFile.Name -f "DarkGreen"
  36.                 $Workbook.SaveAs($savePath)
  37.                 # Added to keep Excel process memory utilization in check
  38.                 $ExcelObj.Workbooks.close()
  39.                 # Move original encryptedFile to $processed_Path
  40.                 Move-Item $encryptedFile.fullname -Destination $processed_Path -Force
  41.             }
  42.             else {
  43.                 $ExcelObj.Workbooks.Close()
  44.             }
  45.         }
  46.     }
  47. $count--
  48. }
  49. # Close Document and Application
  50. $ExcelObj.Workbooks.close()
  51. $ExcelObj.Application.Quit()
  52.  
  53. $endTime = Get-Date
  54.  
  55. Write-Host "Processing Complete!" -f "Green"
  56. Write-Host "Time Started   : " $startTime.ToShortTimeString()
  57. Write-Host "Time Completed : " $endTime.ToShortTimeString()
  58. Write-Host "Total Duration : "
  59. $startTime - $endTime
  60.  
  61. # Remove any stale Excel processes created by this scripts execution
  62. Get-Process excel `
  63. | Where { $currentExcelProcessIDs -notcontains $_.id } `
  64. | Stop-Process
RAW Paste Data