How to open Excel file with password in PowerShell

Published:  

powershell excel


Open an Excel workbook with password in PowerShell.
When executing the Excel book Open method, just pass the password as an option.

Environment

  • Windows 10
  • PowerShell 5.1

Open Excel file with password

$filepath = "C:\path\to\Excel\file.xlsx"
$password = "abcde"

try {
    $excel = New-Object -ComObject Excel.Application
    $excel.Visible = $true
    $excel.DisplayAlerts = $true

    # Open workbook with password
    $wb = $excel.Workbooks.Open($filepath, [Type]::Missing, [Type]::Missing, [Type]::Missing, $password)

    $sheet = $wb.ActiveSheet

    # Some processing

    $wb.Save()

    $excel.Quit()

} finally {
    $sheet, $wb, $excel | ForEach-Object {
        if ($_ -ne $null) {
            [void][System.Runtime.Interopservices.Marshal]::ReleaseComObject($_)
        }
    }
}

Pass the password in the fifth argument of the Open method. Other arguments are omitted by specifying [Type]::Missing.

Please see here if you want to know the meaning of other arguments.

References



Related Posts