PowerShell & BlackBerry Web Services (Part 4 – Coding)

As a summary, in Part 1, we did the necessary prep work.  In Part 2, we looked at the way that we could load the types generated from the BlackBerry Web Services.  In Part 3, we went over the pseudocode that was provided by Research In Motion.

Here in Part 4, we’re actually going to code out some real PowerShell.  I know that everyone’s been waiting for this part.  I’m stepping through the RIM pseudocode exactly from the previous post at this point.  At a point in the future, I’ll probably want to convert some (if not all) of this coding to functions, but for now, this will get the point across.

Step 1 – Create an SSL Ignore policy for this script

As I stated earlier, I’ve totally stolen this little script from the guys over at the PowerShell Code Repository (Link).  I’ll provide my version of this file with this post.

#region Run Trust All Web Clients
. "C:Scripts_SnippetsNew-TrustAllWebClient.ps1"
#endregion Run Trust All Web Clients

Step 2 – Import the Type Definition from the BlackBerry Web Services

Here, we’ll load the DLL that we created for the BlackBerry Web Services Types

#region Import BES Proxy Types
$BesProxy = Add-Type -Path C:ScriptsBlackBerryBesProxy.dll -PassThru
#endregion Import BES Proxy Types

Step 3 – Define some variables that we’ll need for connecting

I’m putting the list of variables here.  Note that I’ve put in generic terms for those entries that are unique to each environment.

#region Variable Definition
$BasFqdn                  = "basconsole.domain.local"
$BasUsername              = "BesWebUser"
$BasPassword              = "PasswordGoesHere"
$BasTimeout               = 60 # seconds
$BasClientVersion         = "5.0.4"
$BasLocale                = "en-US"
$BasOrgId                 = 0
$BasAuthType              = "Blackberry Administration Service"
$BasUserResultSize        = 100
$BasUserSearchDisplayName = "Kevin"
#endregion Variable Definition

The variables are defined like this:

Variable Description
$BasFqdn The Fully Qualified Domain Name of the BAS Instance (or the name of the HA Instance)
$BasUsername The username that BlackBerry Web Services will use to access the BAS
$BasPassword The password that matches the above username.
$BasTimeout The number of seconds that the system uses as a timeout
$BasClientVersion The version of the BlackBerry Environment.  Versions 5.0.3 and 5.0.4 are both acceptable.
$BasLocale The language locale for the request.
$BasOrgId The organization ID within the BAS.  This should always be zero unless you are doing something crazy.
$BasAuthType The type of authentication that you are trying.  The options are “BlackBerry Administration Service” or “Active Directory.”
$BasUserResultSize The number of returns that we want to allow for the user search (Step 10).
$BasUserSearchDisplayName The display name that we’ll search on for the BlackBerry Users.

Step 4 – Create a metadata object that we’ll use for initialization & populate it

This step creates a metadata object that the BlackBerry Web Services requires.  Nothing will work without including a metadata object.  Don’t ask me why.  That information is above my pay grade.

#region Build Metadata Object
$Metadata                 = New-Object -TypeName BesWebService.RequestMetadata
$Metadata.clientVersion   = $BasClientVersion
$Metadata.locale          = $BasLocale
$Metadata.organizationUid = $BasOrgId
#endregion Build Metadata Object

Step 5 – Create & Populate the BWS and BWSUtil Service Connections

Now we need to connect to the BlackBerry Web Service and the BlackBerry Web Utility Service.  We’ll actually authenticate against the BlackBerry Web Service in Step 8.

#region Build BWS Service
$BwsService         = New-Object -TypeName BesWebService.BWSService
$BwsService.Url     = ( "https://" + $BasFqdn + "/enterprise/admin/ws?wsdl" )
$BwsService.Timeout = ( $BasTimeout * 1000 )
#endregion Build BWS Service

#region Build BWS Util Service
$BwsUtilService         = New-Object -TypeName BesWebService.BWSUtilService
$BwsUtilService.Url     = ( "https://" + $BasFqdn + "/enterprise/admin/util/ws?wsdl" )
$BwsUtilService.Timeout = ( $BasTimeout * 1000 )
#endregion Build BWS Util Service

Step 6 – Get an authenticator object

This object is used to authenticate against the web service.  You’ll need to have one for most functions that you try to execute.

#region Build new Authenticator
$AuthRequest          = New-Object -TypeName BesWebService.GetAuthenticatorsRequest
$AuthRequest.metadata = $Metadata
$AuthResponse         = $BwsUtilService.getAuthenticators($Request)

if ( $AuthResponse.returnStatus.code -eq "SUCCESS" )
{
    Write-Host "Authenticator Build Successfully!"
    $BasAuthenticator = $AuthResponse
}
else
{
    Write-Host ( "Authenticator Failed with Message: " + $Response.returnStatus.message )
}
#endregion Build new Authenticator

Step 7 – Create an “encoded” BlackBerry login username

This step just takes the username that we’ve defined in the variables and “encodes” it for use with the BlackBerry Web Services.

#region Build Encoded Username Request
$UsernameRequest                = New-Object -TypeName BesWebService.GetEncodedUsernameRequest
$UsernameRequest.metadata       = $Metadata
$UsernameRequest.username       = $BasUsername
$UsernameRequest.orgUid         = $Metadata.organizationUid
$UsernameRequest.authenticator  = $BesAuthenticator
$credentialType                 = New-Object -TypeName BesWebService.CredentialType
$credentialType.PASSWORD        = $true
$credentialType.value           = $BasPassword
$UsernameRequest.credentialType = $credentialType
$UsernameResponse               = $BwsUtilService.getEncodedUsername($UsernameRequest)

if ( $UsernameResponse.returnStatus.code -eq "SUCCESS" )
{
    Write-Host "Got Encoded Username!"
    $BasEncodedUsername = $UsernameResponse.encodedUsername
}
else
{
    Write-Error "Unable to Get Encoded Username"
}
#endregion Build Encoded Username Request

Step 8 – Connect to the service using the encoded username, password (from variable), and authenticator object.

This step is where we actually connect.  It’s only two lines, but without these, the service would never return anything but errors.

#region Connect to Bes Web Service
$BwsService.Credentials     = New-Object -TypeName System.Net.NetworkCredential ( $BasEncodedUsername, $BasPassword )
$BwsService.PreAuthenticate = $true
#endregion Connect to Bes Web Service

Step 9 – Create a user search request

In this step, we’ll create a user search request, then bind a few more mandatory objects to properties of that request object.  It sounds way harder than it is.

There are two properties of the Get Users request which are actually other objects from the BlackBerry Web Services.  Those are the sortBy object (how to sort the results) and the searchCriteria object (which defines the search type).

#region Build BES Users Request
$BesUserRequest                            = New-Object -TypeName BesWebService.GetUsersRequest
$BesUserRequest.metadata                   = $Metadata
$BesUserRequest.pageSize                   = $BasUserResultSize
$BesUserRequest.sortBy                     = New-Object -TypeName BesWebService.GetUsersSortBy
$BesUserRequest.sortBy.DISPLAY_NAME        = $true
$BesUserRequest.sortBy.value               = "DISPLAY_NAME"
$BesUserRequest.searchCriteria             = New-Object -TypeName BesWebService.GetUsersSearchCriteria
$BesUserRequest.searchCriteria.displayName = $BasUserSearchDisplayName
#endregion Build BES Users Request

Step 10 – Send the search request and get a response

This is literally one line that sends the request and returns the results.  If it’s successful, then we’ve got our users, if not, then something’s amiss.

#region Get BES Users
$BesUserResponse = $BwsService.getUsers( $BesUserRequest )
if ( $BesUserResponse.returnStatus.code -eq "SUCCESS" )
{
    Write-Host "Got User List!"
    $BesUsers = $BesUserResponse.Users
}
else
{
    Write-Error ( "getUsers command returned "+ $BesUserResponse.returnStatus.code )    
}
#endregion Get BES Users

Step 11 – Enumerate the response if successful

This is exactly what it sounds like.  You can do whatever you want with the returned collection (export to a CSV, export to a web page, run them through another function, etc.) but for our environment, we’re just displaying them to the screen.

#region Write Out the BES Users returned from Search
$BesUsers | Select-Object Uid, DisplayName, besHAPoolName, lastContactdate, deviceEnabled | Out-GridView -Title "BlackBerry Users"
#endregion Write Out the BES Users returned from Search

Of course, these are just the first steps for us.  We’ve got lots more to do with these, and I’ll be trying to update everyone with more information as I can.

My next step regarding BlackBerry Web Services & PowerShell will probably revolve around trying to encapsulate most of the above steps into functions.  That will be the beginning of compiling all of this information into a Module or a Snap-in.

Until next time, keep ramblin’ on!

–Kevin

Scripts:

BesWebServices.ps1

New-TrustAllWebClient.ps1

5 thoughts on “PowerShell & BlackBerry Web Services (Part 4 – Coding)”

  1. This is awesome, mate. I was looking for something like this because of BES 10.1 to assign emailprofiles to the user. but i run into a problem @ Step4 gives me the error

    New-Object : Cannot find type [BesWebService.RequestMetadata]: make sure the assembly containing this type is loaded.

    Do you have any idea?

    Regards
    Dan

    Reply

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.