2017-10-07 94 views
0

我試圖找到在網頁中是否存在一個元素:PowerShell的:測試在網頁是否存在一個元素

$ie = New-Object -com InternetExplorer.Application 
$ie.visible = $true 
$ie.Navigate("http://10.0.0.1") 
BrowserReady($ie) # wait for page to finish loading 
if ($ie.Document.getElementById("admin")) { 
    $ie.Document.getElementById("admin").value = "adminuser" 
} 
etc, etc 

(是的,有可能在http://10.0.0.1的頁面不包含元素ID爲「admin」 - 爲什麼沒有關係)

我的問題是,第5行中的測試看起來沒有正常工作:無論元素是否存在,它總是返回TRUE。我也試過

if ($ie.Document.getElementById("admin") -ne $NULL) {...} 

具有相同的結果。

我正在使用Windows 10系統。有任何想法嗎?

+0

因此,在'if'語句中測試 –

+0

D'oh!我正在閱讀它,但認爲它正在測試'不存在' – TessellatingHeckler

回答

1

問題在於你的比較。命令​​返回DBNull,其本身不等於Null。因此,在執行時:

if ($ie.Document.getElementById("admin")) 
{ 
    ... 
} 

您總是會返回True。正如您在以下示例中看到的,$my_element不等於$null,其類型爲DBNull

PS > $my_element = $ie.Document.getElementById("admin") 

PS > $my_element -eq $null 
False 

PS > $my_element.GetType() 

IsPublic IsSerial Name          BaseType                          
-------- -------- ----          -------- 
True  True  DBNull         System.Object 

我建議你使用這個比較的一個,以確定是否爲「admin」確實存在:

PS > $my_element.ToString() -eq "" 
True 

PS > [String]::IsNullOrEmpty($my_element.ToString()) 
True 

PS > $my_element.ToString() -eq [String]::Empty 
True 

如果比較有True返回這意味着價值所以「管理員」不存在。當然,您可以使用-ne以獲得更多便利。

相關問題