2016-04-19 134 views
2

我有一个数组,$常规,我需要循环并点击每次,这样我可以保存在click()后可用的PDF。ForEach循环在PowerShell失败后第一次迭代

$Conventional = @() 
$Conventional = $ie.Document.getElementsByTagName("td") | ? {($_.getAttributeNode('class').Value -match 'NodeDocument') -and ($_.innerText -notmatch 'Library Home')} 

这充满$常规与我需要遍历并点击()每次4个td元素。以下是我的ForEach循环,它在第一次迭代中工作正常,但它然后失败,并且每次都返回System.ComObject

ForEach ($i in $Conventional){ 

    $text = $i.innerText  

    $i.click()    
    while ($ie.Busy -eq $true){Start-Sleep -Seconds 2} 

    $PDF = $ie.Document.getElementById("OurLibrary_LibTocUC_LandingPanel_libdocview1_DocViewDocMD1_hlViewDocument") 

    $currentURL = $PDF.href 
    $fileName = $baseFileName + "_" + $cleanText 

    Invoke-WebRequest -Uri $currentURL -OutFile $NewPath\$fileName.pdf -WebSession $freedom 
} 

这是我捕获的数组的屏幕截图。为了检索PDF,每一个都需要点击。 screenshot of $Conventional array

任何帮助真的不胜感激。谢谢大家

+1

'foreach(){}'有时候COM应用程序返回的集合有问题,因为它们没有正确实现'IEnumerable'。用'$ Conventional | ForEach-Object {$ _。InnerText}'来代替 –

+0

感谢您的回应,现在就试试这个! – Quanda

+0

嗯,同样的问题按照你的建议。在第一次迭代之后,Array是空的,没有任何工作。当我删除$ _click()它会工作并打印innerText,但我需要它与$ _click()一起工作。 Grrrr ... – Quanda

回答

1

既然它工作正常,除非你按下点击,那么点击事件可能会改变文档,足以打破$Conventional-阵列中的元素参考。尝试这种方法:

$linksToProcess = New-Object System.Collections.ArrayList 

$ie.Document.getElementsByTagName("td") | 
Where-Object {($_.getAttributeNode('class').Value -match 'NodeDocument') -and ($_.innerText -notmatch 'Library Home')} | 
Foreach-Object { $linksToProcess.Add($_.innerText) } 

while ($linksToProcess.Count -gt 0){ 

    $i = $ie.Document.getElementsByTagName("td") | ? {($_.getAttributeNode('class').Value -match 'NodeDocument') -and ($_.innerText -eq $linksToProcess[0])} 

    $text = $i.innerText  

    $i.click()    
    while ($ie.Busy -eq $true){Start-Sleep -Seconds 2} 

    $PDF = $ie.Document.getElementById("OurLibrary_LibTocUC_LandingPanel_libdocview1_DocViewDocMD1_hlViewDocument") 

    $currentURL = $PDF.href 
    $fileName = $baseFileName + "_" + $cleanText 

    Invoke-WebRequest -Uri $currentURL -OutFile $NewPath\$fileName.pdf -WebSession $freedom 

    $linksToProcess.RemoveAt(0) 
} 
+0

感谢您的回复。我正在尝试这个。 – Quanda

+1

这个效果非常好,非常感谢你 – Quanda

+0

出于好奇,是否有任何理由选择使用'while'循环并将值从数组中弹出,而不是使用带有计数器的For循环? – Quanda