Sunday, May 30, 2010

A sample of IE automation with power shell

 
# Twitter login name or email
$username_or_email = "xxxxxxxxxxxxxxxx";
# Your twitter password
$password = "xxxxxxxxxxxx";
$url = "http://twitter.com/login";
 
# txt file containing 1 tweet per line
$tweets = Get-Content "$env:USERPROFILE\tweets.txt";
#Interval between tweets
$sleep = 60; 
 
# This is just an attempt to handle the situation where you are already logged into twitter
trap [Exception]
{
 # This will happen if you're already logged in
 if($_.Exception.Message -eq "Property 'value' cannot be found on this object; make sure it exists and is settable." -Or $_.Exception.Message -eq "You cannot call a method on a null-valued expression.")
 {
  # Try and skip this error
  continue;
 }
 else
 {
  # Fail for other Exceptions
  Write-Host -ForegroundColor Red $_.Exception.Message;
 }
}
 
# Create an ie com object
$ie = New-Object -com internetexplorer.application;
$ie.visible = $true;
$ie.navigate($url);
# Wait for the page to load
while ($ie.Busy -eq $true)
{
 Start-Sleep -Milliseconds 1000;
}
 
# Login to twitter
Write-Host -ForegroundColor Green "Attempting to login to Twitter.";
# Add login details
$ie.Document.getElementById("username_or_email").value = $username_or_email;
$ie.Document.getElementById("session[password]").value = $password;
# Click the submit button
$ie.Document.getElementById("signin_submit").Click();
# Wait for the page to load
while ($ie.Busy -eq $true)
{
 Start-Sleep -Milliseconds 1000;
}
 
# Loop through each tweet in the txt file
foreach($tweet in $tweets)
{
 $ie.Document.getElementById("status").value = $tweet;
 $ie.Document.getElementById("status_update_form").Submit();
 Write-Host -ForegroundColor Green "Tweeted; $tweet.";
 Start-Sleep -Seconds $sleep;
 # Check to see if ie is still busy and sleep if so
 while ($ie.Busy -eq $true)
 {
  Start-Sleep -Milliseconds 1000;
 }
}

No comments: