Internet重新连接脚本“您不能在空值表达式上调用方法”错误

时间:2018-09-16 05:54:24

标签: powershell

我正在尝试创建一个脚本,当我的Internet断开连接时,它会自动重新连接并登录到Wifi。但是,出现无法登录脚本的错误。

while (Test-Connection 8.8.8.8 -Quiet) {
}

netsh wlan connect wifi-name

$ie = New-Object -Com InternetExplorer.Application 
$ie.Visible = $false
$ie.Navigate("http://address/loginpage.php") 

$link = $ie.Document.GetElementById("btnLogin")
$link.Click()

$ie.Quit()

它返回此错误:

You cannot call a method on a null-valued expression.
At line:12 char:1
+ $link = $ie.Document.GetElementById("btnLogin")
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [], RuntimeException
    + FullyQualifiedErrorId : InvokeMethodOnNull

You cannot call a method on a null-valued expression.
At line:13 char:1
+ $link.Click()
+ ~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [], RuntimeException
    + FullyQualifiedErrorId : InvokeMethodOnNull

我确保ID也正确:

Screenshot

1 个答案:

答案 0 :(得分:1)

一种可能性是IE尚未完成页面加载。这可能是因为它正在尝试加载代理自动配置文件,与MS联系以获取新的标签供稿或类似内容。

尝试添加对IE的busy属性的检查,以查看该文档何时准备就绪。像这样

$ie = New-Object -com internetexplorer.application
$ie.visible = $false
$ie.navigate($url)

# Sleep while IE is busy. Check 10 times per second, adjust delay as needed
while($ie.Busy) { Start-Sleep -Milliseconds 100 }

# IE is not busy with document anymore, do stuff