在 powershell 中打开密码保护 Excel

open a password protected Excel in powershell

我正在尝试在 powershell 中打开受密码保护的 excel sheet 并输出有关 sheet.

中有多少行的报告

如果 sheet 没有密码保护,脚本绝对可以正常工作,但如果设置了密码,我似乎无法通过 powershell 打开它。

我当前的脚本是

$Report = "S:\Business Support\excel tests\MI Tool - Live.csv"
$path = "S:\Business Support\excel tests"
[Array]$Results = $null
$excelSheets = Get-Childitem -Path $path -Include "MI Tool - Live.xlsm" -Recurse
$excel = New-Object -comobject Excel.Application
$excel.visible = $false
$password = "blablabla"
$updatelinks = 0


foreach($excelSheet in $excelSheets)
{
 $workbook = $excel.Workbooks.Open($excelSheet,$updatelinks,$password)
 $rowCount = $null

  $worksheet = $workbook.sheets.item("Data")
  $rowMax = ($worksheet.usedRange.rows).count
  $rowCount += $rowMax

$Results += New-Object Psobject -Property @{
    "File Name"=$excelSheet.Name
    "Row Count"=$rowCount}
$excelSheet.Name
$workbook.Sheets.count
$rowCount
}
$excel.quit()
Stop-Process -Name EXCEL -Force
$Results | select "File Name","Row Count" | Export-Csv $Report -NoTypeInformation

这是我得到的错误:

Exception calling "Open" with "3" argument(s): "Open method of Workbooks class failed"
At line:3 char:35
+  $workbook = $excel.Workbooks.Open <<<< ($excelSheet,$updatelinks,$password)
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : ComMethodTargetInvocation

You cannot call a method on a null-valued expression.
At line:5 char:37
+   $worksheet = $workbook.sheets.item <<<< ("Data")
    + CategoryInfo          : InvalidOperation: (item:String) [], RuntimeException
    + FullyQualifiedErrorId : InvokeMethodOnNull

如果我取出 $password 变量,它就可以工作,但我必须手动输入密码。

您的 Open 重载不正确。密码是第 5 个变量。 Have a look at MSDN to see

expression .Open(FileName, UpdateLinks, ReadOnly, Format, Password, WriteResPassword, IgnoreReadOnlyRecommended, Origin, Delimiter, Editable, Notify, Converter, AddToMru, Local, CorruptLoad)

所以我认为您需要先填充 ReadOnly 和 Format。您必须填充这些值。

$excel.Workbooks.open($path,0,0,5,$password)

查看 MSDN 以了解 2、3 和 4 位置中的值代表什么。