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

时间:2018-01-08 06:33:14

标签: windows powershell internet-explorer scheduled-tasks taskscheduler

我的大学要求所有计算机执行基于网络的登录才能访问互联网,并声称所有用户都会在午夜自动注销(听起来很奇怪,但确实如此),所以我正在尝试编写一个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:\WINDOWS\system32\WindowsPowerShell\v1.0\powershell.exe -ExecutionPolicy RemoteSigned -File C:\Users\MyName\Documents\Powershell\login_IE.ps1

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

C:\WINDOWS\system32\WindowsPowerShell\v1.0\powershell.exe

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

-ExecutionPolicy RemoteSigned -File C:\Users\MyName\Documents\Powershell\login_IE.ps1

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

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

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

1 个答案:

答案 0 :(得分:0)

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

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

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

[Net.ServicePointManager]::SecurityProtocol = 
[Net.SecurityProtocolType]::Tls12

希望这对其他人有帮助。