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

问题描述

我正在尝试编写一个脚本,当我的 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()

它返回此错误:

您不能在空值表达式上调用方法。
在行:12 字符:1
+ $link = $ie.Document.GetElementById("btnLogin")
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo : InvalidOperation: (:) [], RuntimeException
    + FullyQualifiedErrorId : InvokeMethodOnNull

您不能在空值表达式上调用方法。
在行:13 字符:1
+ $link.Click()
+ ~~~~~~~~~~~~~
    + CategoryInfo : InvalidOperation: (:) [], RuntimeException
    + FullyQualifiedErrorId : InvokeMethodOnNull

我已确保 ID 也是正确的:

截屏

标签: powershell

解决方案


一种可能性是 IE 尚未完成页面加载。这可能是因为它正在尝试加载代理自动配置文件,联系 MS 以获取新的选项卡提要等。

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

$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

推荐阅读