在PowerShell中打开密码保护的Excel

我试图在PowerShell中打开一个密码保护的Excel工作表,并输出一个报表中有多less行。

该脚本工作绝对好,如果工作表没有密码保护,但我似乎无法得到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 

如果我拿出$密码variables它的作品,但我必须手动input密码。

您的开放超载是不正确的。 密码是第五个variables。 看看MSDN看看

expression式.Open(FileName,UpdateLinks,ReadOnly,格式, 密码 ,WriteResPassword,IgnoreReadOnlyRecommended,起源,分隔符,可编辑,通知,转换器,AddToMru,本地,CorruptLoad)

所以你需要首先填充ReadOnly和Format我相信。 你将不得不填充这些值。

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

看看MSDN,了解这些值在2,3和4的位置。