从Powershell中的Excel文件中删除密码

时间:2019-07-05 12:00:52

标签: excel powershell excel-interop

我一直在使用@inwenis通过http://pastebin.com/UCqXUYHU提供的代码

它似乎可以正常工作,并且将删除文件夹中文件的一个或两个密码,但是在2个已解决的excel工作表或密码列表中的密码少于30行之后失败。 谁能指出我的错误所在,原因可能是自动处理超过2张纸或更大的密码列表。

      param(
        $encrypted_path = "C:\PoShTest\Encrypted\",
        $decrypted_Path = "C:\PoShTest\Decrypted\",
        $processed_Path = "C:\PoShTest\Processed\",
        $password_Path  = "C:\PoShTest\Passwords\Passwords.txt"
    )
    $ErrorActionPreference = "SilentlyContinue"

    # Get Current EXCEL Process ID's so they are not affected by the scripts cleanup
    $currentExcelProcessIDs = (Get-Proces s excel).Id
    $startTime = Get-Date

    Clear-Host

    $passwords = Get-Content -Path $password_Path
    $encryptedFiles = Get-ChildItem $encrypted_path
    [int] $count = $encryptedFiles.count - 1
    $ExcelObj = New-Object -ComObject Excel.Application
    $ExcelObj.Visible = $false
    $encryptedFiles | % {
        $encryptedFile  = $_
        Write-Host "Processing" $encryptedFile.name -ForegroundColor "DarkYellow"
        Write-Host "Items remaining: " $count
        if ($encryptedFile.Extension -like "*.xls*") {
            $passwords | % {
                $password = $_
                # Attempt to open encryptedFile
                $Workbook = $ExcelObj.Workbooks.Open($encryptedFile.fullname, 1, $false,5, $password)
                $Workbook.Activate()

                # if password is correct save decrypted encryptedFile to $decrypted_Path
                if ($Workbook.Worksheets.count -ne 0 ) {
                    $Workbook.Password = $null
                    $savePath = Join-Path $decrypted_Path $encryptedFile.Name
                    Write-Host "Decrypted: " $encryptedFile.Name -f "DarkGreen"
                    $Workbook.SaveAs($savePath)
                    # Added to keep Excel process memory utilization in check
                    $ExcelObj.Workbooks.close()
                    # Move original encryptedFile to $processed_Path
                    Move-Item $encryptedFile.fullname -Destination $processed_Path -Force
                }
                else {
                    $ExcelObj.Workbooks.Close()
                }
            }
        }
    $count--
    }
    # Close Document and Application
    $ExcelObj.Workbooks.close()
    $ExcelObj.Application.Quit()

    $endTime = Get-Date

    Write-Host "Processing Complete!" -f "Green"
    Write-Host "Time Started   : " $startTime.ToShortTimeString()
    Write-Host "Time Completed : " $endTime.ToShortTimeString()
    Write-Host "Total Duration : " 
    $startTime - $endTime

# Remove any stale Excel processes created by this scripts execution
Get-Process excel `
| Where { $currentExcelProcessIDs -notcontains $_.id } `
| Stop-Process

0 个答案:

没有答案
相关问题