Powershell Internet Explorer Automation
November 23, 2017
Today we will be looking into Internet Explorer (IE) automation, using Powershell.
What this script will do :
- Open an instance of IE
- Navigate to a certain webpage
- Fill in credentials
- Click button to login
First let’s open up Powershell ISE; press the windows button and start typing “powershell”, it should appear in the results pane.
1.Open an instance of IE
To open a instance of IE, we are going to use :
$ie = new-object -com "InternetExplorer.Application"
$ie.visible = "true"
The first line will create the IE instance, and the second line is setting the visibility of the window, because as default it is hidden. You can test this by removing the second line, the script will run fine but you will not be able to see anything.
2.Navigate to certain webpage
Next to navigate to a certain URL, we can set the address to a variable like below:
$siteURL = "http://www.leokim.co.nz/testpage.php"
$ie.navigate($siteURL)
or just type in the URL in quotations, either way works fine.
$ie.navigate("http://www.leokim.co.nz/testpage.php")
3.Fill in credentials
Before filling in credentials, it is important to wait for the page to finish loading.
while ($ie.ReadyState -ne 4)
{
start-sleep -s 1;
}
What this is basically saying is, “while my internet explorer ready state is not equal to 4, keep sleeping 1 second.
Next we need to use a bit of JavaScript to select the username and password input boxes.
$usernameField = $ie.document.getElementById("UN");
$passwordField = $ie.document.getElementById("PW");
To fill in the values :
$usernameField.value = "myUsername";
$passwordField.value = "myPassword";
4.Click button to login
As we’ve done previously, we need to select the submit button, I’ve thrown in a 1 second delay in between because I like pauses…
$btn_Submit = $ie.document.getElementById("submit1");
start-sleep -s 1;
$btn_Submit.click()
There we have it, to put it all together :
$ie = new-object -com "InternetExplorer.Application"
$ie.visible = "true"
$siteURL = "http://www.leokim.co.nz/testpage.php"
$ie.navigate($siteURL)
while ($ie.ReadyState -ne 4)
{
start-sleep -s 1;
}
$usernameField = $ie.document.getElementById("UN");
$passwordField = $ie.document.getElementById("PW");
$usernameField.value = "myUsername";
$passwordField.value = "myPassword";
$btn_Submit = $ie.document.getElementById("submit1");
start-sleep -s 1;
$btn_Submit.click()
Today we looked into a very simple automation script, next post I will try to cover:
- Inspecting elements using the IE/Chrome Developer Tools
- Selecting elements that do not have an ID