This one’s a little bit more obscure than usual as I’m not sure how many people use SmartBear Software’s AlertSite service or not. If not, then this should be a good demonstration of how we can use PowerShell to connect to remote REST APIs and then sync the parsed XML response/information to a custom SharePoint List :). On the otherhand, if you don’t care about SharePoint then this demo would also be a good code sample for the .NET crowd as well since AlertSite only has sample code using Perl.

This script assumes that there is a custom SharePoint List created with the following fields:

Title – Single Line of Text (default)
MonitorInterval – Number
BeingMonitored – Yes/No
NotifyOnError – Yes/No
Traceroute – Yes/No
MonitorTimeout – Number

Once you create the fields using the names above, feel free to change the display names. The script will work with the internal field names that are static.

Click here to download the PS1.

PowerShell Script pasted below for search purposes.
You may need to highlight and copy the script below into notepad to be able to read all of the characters that were chopped off by this blog’s layout.

######################################################################################################
# This script will log into AlertSite's REST API and sync the account's devices with a SharePoint List
#
# Author: Henry Ong
#
# AlertSite Documentation: 
# http://help.alertsite.com/AlertSite/RestAPI?skin=clean.nat%2cnat#5_1_Example_of_Report_API
######################################################################################################

############# Start Variables ################
$RESTServer = "https://www.alertsite.com/restapi"
$login = "YourEmailAddress"
$password = "YourPassword"
$postLogin = "<Login><Login>$login</Login><Password>$password</Password></Login>"
$devicesRequest = "<List><APIVersion>1.1</APIVersion><TxnHeader><Request><Login>$login</Login><SessionID>$sessionID</SessionID></Request></TxnHeader><Source></Source></List>"
$SPWebURL = "YourSharePointSiteURL"
$SPListName = "AlertSite Devices"
############# End Variables ##################

[System.Reflection.Assembly]::LoadWithPartialName("System.Net")
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint")

##############################################
## Setup user agent and login request
##############################################
$encode = [System.Text.Encoding]::UTF8
$loginBytes = $encode.GetBytes($postLogin)

## Creating and posting a request to AlertSite's REST API Login page
$req = [System.Net.WebRequest]::Create($RESTServer + "/user/login")
$req.Method = "POST"
$req.ContentType = "text/xml"
$req.ContentLength = $loginBytes.Length
$req.UserAgent = "AlertSite REST Client/1.0"

$reqStream = $req.GetRequestStream()
$reqStream.Write($loginBytes, 0, $loginBytes.Length)
$reqStream.Close()

## Working with the response sent back from AlertSite
$resp = $req.GetResponse()
$cookie = $resp.Headers["Set-Cookie"]

$responseStream = $resp.GetResponseStream()
$respReader = (New-Object System.IO.StreamReader($responseStream))
$XMLResponse = $respReader.ReadToEnd()
$responseStream.Close()

# Save Session ID and Customer Object ID for subsequent API calls
$XMLEncoded = [xml]$XMLResponse

$sessionID = $XMLEncoded.Response.SessionID
$objCust = $XMLEncoded.Response.ObjCust
$resp.Close()

##############################################
## Getting the list of devices from AlertSite
##############################################

$encode = [System.Text.Encoding]::UTF8
$listDeviceBytes = $encode.GetBytes($devicesRequest)

$req = [System.Net.WebRequest]::Create($RESTServer + "/devices/list")
$req.Method = "POST"
$req.ContentType = "text/xml"
$req.ContentLength = $listDeviceBytes.Length
$req.UserAgent = "AlertSite REST Client/1.0"
$req.Headers.Add("Cookie", $cookie)

$reqStream = $req.GetRequestStream()
$reqStream.Write($listDeviceBytes, 0, $listDeviceBytes.Length)
$reqStream.Close()

$resp = $req.GetResponse()

$responseStream = $resp.GetResponseStream()
$respReader = (New-Object System.IO.StreamReader($responseStream))
$XMLResponse = $respReader.ReadToEnd()
$responseStream.Close()

$XMLEncoded = [xml]$XMLResponse
$resp.Close()

###########################################
# Update SharePoint List
###########################################

$site = New-Object Microsoft.SharePoint.SPSite($SPWebURL)
$web = $site.OpenWeb()
$deviceList = $web.Lists[$SPListName]

foreach($device in $XMLEncoded.Response.TxnList.Txn)
{
    $deviceName = InjectSpaces $device.TxnName
    $interval = $device.TxnDetail.GetAttribute("Interval")
    $monitored = ReturnBoolFromLetter $device.TxnDetail.GetAttribute("Monitor")
    $notify = ReturnBoolFromLetter $device.TxnDetail.GetAttribute("Notify")
    $traceRoute = ReturnBoolFromLetter $device.TxnDetail.GetAttribute("TraceError")
    $timeout = $device.TxnDetail.GetAttribute("TimeOut")

    $listItem = FindDeviceInSharePoint $deviceName

	if($listItem -eq $null)
    {        
        CreateNewListItem $deviceList $deviceName $interval $monitored $notify $traceRoute $timeout
    }

    elseif($listItem -ne $null)
    {
        UpdateListItem $listItem $deviceName $interval $monitored $notify $traceRoute $timeout
    }

}

$spweb.dispose()
$spsite.dispose()

####################################################################################################
## This function will replace the "%20" characters in the string with spaces.
####################################################################################################
function InjectSpaces($string)
{
	$newString = $string.replace("%20", " ")
	return $newString
}

####################################################################################################
## This function will return the SharePoint List Item that represents the device if it exists.
####################################################################################################
function FindDeviceInSharePoint($device)
{
	$listQuery = New-Object Microsoft.SharePoint.SPQuery
	$listQuery.Query = "<Where><Eq><FieldRef Name='Title' /><Value Type='Text'>" + $device + "</Value></Eq></Where>"
	$itemCollection = $deviceList.GetItems($listQuery)
	if($itemCollection.count -eq 1)
	{
		return $itemCollection[0]
	}
	else
	{
		return $null 
	}
}

####################################################################################################
## This function will create a new SharePoint List Item to represent the AlertSite Device if 
## it doesn't exist.
####################################################################################################
function CreateNewListItem($spList, $deviceName, $monitorInterval, $beingMonitored, $notifyOnError, $traceRouteOnError, $monitorTimeout)
{
    $listItem = $spList.Items.Add()
    $listItem["Title"] = $deviceName
    $listItem["MonitorInterval"] = $monitorInterval
    $listItem["BeingMonitored"] = $beingMonitored
    $listItem["NotifyOnError"] = $notifyOnError
    $listItem["Traceroute"] = $traceRouteOnError
    $listItem["MonitorTimeout"] = $monitorTimeout
    $listItem.update()
}

####################################################################################################
## This function will update an existing SharePoint List Item that represents an AlertSite Device.
####################################################################################################
function UpdateListItem($listItem, $deviceName, $monitorInterval, $beingMonitored, $notifyOnError, $traceRouteOnError, $monitorTimeout)
{
    $listItem["MonitorInterval"] = $monitorInterval
    $listItem["BeingMonitored"] = $beingMonitored
    $listItem["NotifyOnError"] = $notifyOnError
    $listItem["Traceroute"] = $traceRouteOnError
    $listItem["MonitorTimeout"] = $monitorTimeout
    $listItem.update()
}
####################################################################################################
## This function will convert the AlertSite attributes for SharePoint consumption.
####################################################################################################
function ReturnBoolFromLetter($letter)
{
    if($letter -eq "y")
    {
        return $true
    }

    elseif($letter -eq "n")
    {
        return $false
    }
}
Advertisements