运行 Powershell 脚本以从任务计划执行自动网页登录的行为与手动运行脚本的行为不同



我的大学要求所有计算机执行基于Web的登录才能访问互联网,并声称所有用户将在午夜自动注销(听起来很奇怪,但这是真的),所以我正在尝试编写一个powershell脚本(在Windows 10中)在午夜执行自动登录。

我的脚本在这里列出。它在后台打开IE进程(以不可见的方式),填写用户名和密码,登录并终止IE进程。

# If there are existing Internet Explorer processes, close it
$IE_Process = Get-Process iexplore -ErrorAction Ignore
if ($IE_Process) { 
$IE_Close = Foreach-Object { $IE_Process.CloseMainWindow() } 
}
Stop-Process -Name "iexplore" -ErrorAction Ignore
# Login Information
$url = "http://xxx.xxx.xxx.xxx/"
$username = "xxxxxxxx" 
$password = "xxxxxxxx" 
# Open an IE process
$ie = New-Object -com internetexplorer.application; 
$ie.silent = $true 
$ie.navigate($url); 
while ($ie.Busy -eq $true) 
{ 
Start-Sleep -s 1; 
} 
# The stupid webpage needs to submit twice
$ie.Document.getElementById("loginname").value = $username 
$ie.Document.getElementByID("password").value = $password 
$ie.Document.getElementById("button").Click()
Start-Sleep -s 1; 
$ie.Document.getElementById("loginname").value = $username 
$ie.Document.getElementByID("password").value = $password 
$ie.Document.getElementById("button").Click()
# Close the IE process
$IE_Process = Get-Process iexplore -ErrorAction Ignore
if ($IE_Process) { 
$IE_Close = Foreach-Object { $IE_Process.CloseMainWindow() } 
}
Stop-Process -Name "iexplore" -ErrorAction Ignore
Remove-Variable -Name ie,username,password,url,IE_Process -ErrorAction Ignore

脚本保存为"login_IE.ps1"。它可能写得很差,因为我是 powershell 的新手,但它有效。如果我打开一个cmd窗口并执行以下命令,我已登录。

C:WINDOWSsystem32WindowsPowerShellv1.0powershell.exe -ExecutionPolicy RemoteSigned -File C:UsersMyNameDocumentsPowershelllogin_IE.ps1

但是,如果我在执行此脚本的 Windows 任务计划程序中创建一个计划任务,它不起作用。我将"程序/脚本:"填写为:

C:WINDOWSsystem32WindowsPowerShellv1.0powershell.exe

并将"添加参数(可选):"填写为:

-ExecutionPolicy RemoteSigned -File C:UsersMyNameDocumentsPowershelllogin_IE.ps1

计划任务在我的帐户下运行(我是此计算机的唯一用户)。

如果我手动运行计划任务,在任务管理器中我可以看到在"后台进程"中打开了两个IE进程,与互联网通信,然后被杀死,所以我很确定脚本实际上已经执行。但是我发现我没有登录,因为我无法访问互联网,问题可能在哪里?

任何建议都非常感谢。提前谢谢。

我遇到的类似类型的问题,当尝试直接从Powershell窗口运行脚本时,它按预期工作,但从任务计划程序或命令行都没有获得预期的结果。

在我的脚本中注释和添加如下所示的行,帮助我从命令行和任务计划程序运行脚本

$AllProtocols = [System.Net.SecurityProtocolType]'Ssl3,Tls,Tls11,Tls12'
[System.Net.ServicePointManager]::SecurityProtocol = $AllProtocols
[Net.ServicePointManager]::SecurityProtocol = 
[Net.SecurityProtocolType]::Tls12

希望这对其他人有所帮助。

最新更新