我正在尝试在PowerShell中打开受密码保护的Excel工作表,并输出有关工作表中有多少行的报告。
如果工作表没有密码保护,脚本工作得非常好,但是如果设置了密码,我似乎无法使用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变量,它可以工作,但我必须手动输入密码。
答案 0 :(得分:3)
您的Open过载不正确。密码是第5个变量。 Have a look at MSDN to see
表达式.Open(FileName,UpdateLinks,ReadOnly,Format,密码,WriteResPassword,IgnoreReadOnlyRecommended,Origin,Delimiter,Editable,Notify,Converter,AddToMru,Local,CorruptLoad)
所以你需要先填充ReadOnly和Format,我相信。你必须填充这些值。
$excel.Workbooks.open($path,0,0,5,$password)
查看MSDN以了解值在2,3和4位置中的含义。