IE Automation with Powershell

2020-03-24 04:24发布

问题:

I am attempting to automate the login to website on our intranet using Powershell and IE. So far, I have the following code that works:

$ie = new-object -com "InternetExplorer.Application" 
$ie.navigate("https://somepage/jsp/module/Login.jsp/")
while($ie.ReadyState -ne 4) {start-sleep 1} 
$ie.visible = $true 
$doc = $ie.Document
If ($doc.nameProp -eq "Certificate Error: Navigation Blocked") {
    $doc.getElementByID("overridelink").Click()
}
$loginid = $doc.getElementById("loginid") 
$loginid.value= "username"
$password = $doc.getElementById("password")
$password.value = 'somepass'
$ie.navigate("javascript:doSubmit('login')",$null,$true)

So, the problem area I have now is that the site closes the original window used to login and opens a new IE window. How do I go about submitting inputs to that new window? I know I can use something like tasklist.exe /v to get the PID of the new window... but I'm not sure how I would go about taking control of it.

Also, after viewing my code, please know I do not intend to use embedded user name and passwords. That's only in place so that I don't have to continually type a un/pw combo every time I want to test the script.

回答1:

After trying a bit more...

$applist = new-object -com shell.application
$newie = $applist.windows() | where {$_.Type  -eq "HTML Document" -and $_.LocationURL -match "MainFrame.jsp"}


回答2:

I found an old article that describes how to do what you're looking for, by looping through the windows of a Shell.Application object. I have to say that while it looks possible and does seem to answer your direct question, the approach seems pretty unpleasant and fragile to me.

If you're not averse to trying a different approach, I would suggest giving Selenium Webdriver a shot. You can use the Internet Explorer driver, and the C# examples in the documentation generally translate nicely into PowerShell. You get some other nice benefits too, like drivers for other web browsers or the ability to wait for a condition instead of relying on sleep/check loops. You will also have a driver.switchTo() function that allows you to bounce between windows or frames.



回答3:

Try this.

  1. $shell = (New-Object -ComObject Shell.Application).Windows()
  2. $shell.Count
  3. 7
  4. you have items 0-6 you can check this way.
  5. $shell.Item(0).LocationName
  6. or
  7. $shell.Item(0).LocationURL
  8. $shell.Item(1).LocationName
  9. $shell.Item(1).LocationURL