Showing posts with label PowerShell. Show all posts
Showing posts with label PowerShell. Show all posts

Thursday, January 4, 2018

Finding likes between two arrays

In a recent interview I was asked to write a function to sole the following problem:

You have a SQL query and two arrays, find the like elements between the two arrays.

(I am assuming that a few of you have your own opinions on how to solve this, and that is excellent - please enlighten me)

The first thought that popped into my head was that this was not a coding interview, the second was that i really needed a laptop to work through this, and the third was - doesn't PowerShell have a cmdlet that will do this for me?

Back at home, I thought I would investigate the PowerShell angle.  Since I had access to a laptop.
I am assuming a small dataset

First, lets build a couple arrays to validate with:

$array1 = "Elmer", "hunter", "Bugs", "rabbit", "Tweety", "bird", "Sylvester", "feline"
$array2 = "Eddie", "investigator", "Roger", "rabbit", "Jessica", "rabbit", "Judge", "doom", "tweety", "bird"

Now, I did add some variation for fun.  Because why might this be an important skill?
It might be important because I might need to mine a bunch of data or logs to investigate a pattern.

At this point I have arbitrarily added an additional requirement on myself; I want to see all of the matched data items, not just the matched values.  Equivalents vs. equals if you will.
Why? Again, in an investigation I will probably want to use a fuzzy match instead of a literal match.  And then I will want to work through the resulting set again.  (most likely both with eyes and with code).

In regards to PowerShell doing this for me, I discovered this:

$compared = Compare-Object -ReferenceObject $array1 -DifferenceObject $array2 -IncludeEqual

But when looking at the output, working with this is not very intuitive and it hides my fuzzy match and detail output.

PS C:\Users\Brian> $compared

InputObject  SideIndicator
-----------  -------------
rabbit       ==
Tweety       ==
bird         ==
Eddie        =>
investigator =>
Roger        =>
Jessica      =>
rabbit       =>
Judge        =>
doom         =>
Elmer        <=
hunter       <=
Bugs         <=
Sylvester    <=
feline       <=

I actually ended up going back to my original idea; 

$likes = @()

foreach ($element1 in $array1){
    foreach ($element2 in $array2){
        if ($element1 -like $element2){
            $likes += $element1;
            $likes += $element2;
        }
    }
}

while not highly efficient and I am sure not wonderful with large data sets, it does give me the results that I wanted for further analysis:

PS C:\Users\Brian> $likes
rabbit
rabbit
rabbit
rabbit
Tweety
tweety
bird
bird

It is easy to see from this output where I might want to go next; counts, deeper analysis, trends, etc.  It all depends on the details in the records used.

If you have different ideas that meet my requirements, please share.


Friday, January 27, 2017

Creating custom devices in Octoblu

Part 1: Use configuration events in Octoblu

This is something that I have been playing with for a very long time.
I directly use the Octoblu API to create my own devices.

I have copied existing devices, and I have created entirely new devices.
In this post I am going to create an entirely new device so that I can take advantage of the state (properties) feature to persist and evaluate data.

Why am I doing this instead of just reusing an existing Device?  Primarily because this makes a much easier to digest configuration change message on the listen side later on.  As there is a bare minimum number of properties.

Part 2 - Create a custom Octoblu device

Up front - I am a hard core Windows user (I do use Linux as well, but I have never used MAC) so my code example is in PowerShell.

Why would I create a custom device?
Well, my 'Thing' is an abstraction and not a physical device.

In practice, I have created 'rooms' in which I save data (aka set properties) from multiple sources or flows.  And I listen to specific data (property) changes of this device and then act on that data.

To do this there are a few things involved;
  • your security uuid and token
  • defining the security of the device
  • defining any custom properties of the device (if you want)
  • defining the base properties
  • performing the POST
  • looking at what you get back
Much of what is in the PowerShell below is all about building the object as a PowerShell object before it is converted to a JSON object.  Making sure that the data format is correct (arrays in the proper places, lists in the proper places, etc.)

# Octoblu User account (check your user properties)
$meAuthHeader = @{
    meshblu_auth_uuid = ''  
    meshblu_auth_token = ''
}


### build the JSON

# define the device permissions
$user = @()
$user += @{ uuid = $meAuthHeader.meshblu_auth_uuid }
$anyone = @()
$anyone += @{ uuid = '*' }
$empty = @()
$configureWhitelist = @{
    as = $empty;
    received = $empty;
    sent = $empty;
    update = $user
}
$message = @{
    as = $empty;
    received = $empty;
    sent = $anyone
}
$discover = @{
    as = $empty;
    view = $user
}
$broadcast = @{
    as = $empty;
    received = $anyone;
    sent = $anyone
}
$whitelists = @{
    configure = $configureWhitelist;
    message = $message;
    discover = $discover;
    broadcast = $broadcast
}

# define the schema of the device (behaviors and properties)

$properties = @{
    rooms = @{
        title = "sensors";
        type = "array";
        readonly = $true;
        items = @{
            type = "string"
        }
    }
}
$configure = @{
    Default = @{
        type = "object";
        properties = $properties;
        'x-form-schema' = @{
            angular = "configure.Default.angular"
        }
    }
}

$options = @{
    title = "Options";
    type = "object";
    properties = $properties
}
$configure = @{
    Default = @{
        title = "My Entity";
        type = "object";
        properties = @{
            options = $options
        };
        'x-form-schema' = @{
            angular = "configure.Default.angular"
        }
    }
}

$fields = @()
$fields += @{ key = "options.rooms" }
$form = @{
    configure = @{
        Default = @{
        angular = $fields
        }
    }
}

# wrap the above in the proper keys

$schemas = @{
    configure = $configure;
    form = $form;
    version = "2.0.0"
}

$meshblu = @{
    version = "2.0.0";
    whitelists = $whitelists;
}

# basic 'properties' (aka key:values) of the Device

$body = @{
    online = $true;
    owner = $meAuthHeader.meshblu_auth_uuid;
    type = "device:myDeviceType";
    name = "myDeviceName";
    city = "Redmond";
    meshblu = $meshblu;
    schemas = $schemas
}

# convert the PowerShell object to a JSON object

$json_body = $body | ConvertTo-Json -Depth 99

### create the device

$device = Invoke-RestMethod -URI http://meshblu-http.octoblu.com/devices -ContentType "application/json" -body $json_body -Method Post

$device | ConvertTo-Json -Depth 99


Now record the uuid and token of your device.  This is the ONLY time you get this token back, and you would need to generate a new one to know it again.

Also, you can set other properties such as a 'logo'.  For the logo the value must be an HTTPS URL reference to an SVG.

Next up:  Setting properties from a flow to this device.

Wednesday, March 16, 2016

PowerShell to the Philips Hue API

If you have been to HPE Discover London 2015, Aruba Atmosphere 2016, CeBIT 2016 or you are going to Citrix Synergy 2016 you will have an opportunity to experience the Collaborate Cube(d).

https://twitter.com/hpecollaborate

I have been working with the Cube (making it do its song and dance) and related technologies for nearly two years.

This is an IoT thing.  But what we are driving and the place we are operating is not what most folks thing of as IoT.
This is about taking context (a person, a physical place, the capabilities of a space, and what is relevant at this moment in time) and tying them all together into a set of context specific actions (capabilities, events, controls - call it what you will).

The actions are relevant to this time and place.

One of the actions in the Cube is setting lights around the glass enclosure to red (the room is busy) or green (the room is available).

This sounds pretty simple on the surface.  You hook up a Philips Hue then you link it in, then you send some commands.  Actually, it is rather simple.  Except one part that is not entirely obvious to most folks (that aren't makers nor developers), and that is getting that first connection in the first place.

In helping to set the Cube up at three venues now, the Hue connection still seems to be one of the more complex things.  Especially when you Hue is brand new (which of course it is at each show :-S  ).

So, I have a little PowerShell script that will give you what you need to:
  1. create a valid user in your local Hue bridge
  2. get the information you need to connect to that
Of course I am using Octoblu to control the Hue.  Why wouldn't I?  There are some decent instructions for getting things set up. (see Step 4, then instead of 3 come back here, then 5).
But they send you off to an API document to sort out the one critical getting started piece, getting connected.  And then Philips hides their API guide behind a registration gate.  Double whammy.  Too much effort.  Walk away.

Here is my script, with comments, to get you started.
And after you get hooked up, there is most likely enough guidance in this script for you to simply play with the Philips Hue API.  ;-)

You can copy, save, and run this script and it should do everything you need.

# Associate your Hue Bridge with Octoblu.
# These are the setup things you need to do.

# find the Hue on your local network - this assumes you have only one
$hueIp = Invoke-RestMethod -URI https://www.meethue.com/api/nupnp
$ip = $hueIp[0].internalipaddress

$gatebluName = Read-Host -Prompt "Enter the name of your Gateblu"

Do {
    if ( !$hueUser ) {
        Write-Host -ForegroundColor Black -BackgroundColor White "Press the button on the top of the Hue bridge."
    }
    elseif ( $hueUser.error.description ) {
        Write-Host -ForegroundColor Black -BackgroundColor White $hueUser[0].error.description
    }
   
    Read-Host -Prompt "Enter to continue"

    #Hue create account
    $body = @{ "devicetype" = "gateblu#$gatebluName" }
    $json_body = $body | ConvertTo-Json
    $hueUser = (Invoke-RestMethod -URI http://$ip/api -ContentType "application/json" -body $json_body -Method Post -ErrorAction SilentlyContinue)[0]

} until ( $hueUser.success )

$apiUsername = $hueUser.success.username

Write-Host "Open the Philis Hue Thing in Octoblu interface"
Write-Host "Select the Gateblu instance to connect to"
Write-Host "Enter: $ip as the ipAddress"
Write-Host "Enter: $apiUsername as the apiUsername"

# Return the full state
$hueState = Invoke-RestMethod -URI http://$ip/api/$apiUsername -ContentType "application/json" -Method Get -ErrorAction SilentlyContinue

"Configured Lights:"
$hueState.lights | Format-List

"Configured Groups:"
$hueState.groups

# Full configuration
# $hueState.config



Tuesday, December 1, 2015

Error handling can make or break an experience

This post is a bit of an adventure in building a very small piece of a rather cool demo.
It is really an adventure in developing thorough unit tests.

Some of you have probably noticed that my blog has been kind of dead for a pretty long stretch.  Needless to say, I have been busy.

This week is HP Discover in London.  It is a really big show for HP.

There is a demo called Collaboration Cubed.  And I must say, it is pretty cool.
https://twitter.com/JordanTechPro/status/671698781965021188

This is all about building an experience more than it is about building software.

There is this big glass cube, with two monitors, a table, three Surface tablets, and more.
You walk in with a phone, you are recognized. 
You are welcomed by a synthetic voice. 
The room is tagged as occupied. 
Your cohorts come into the room.
A Lync meeting begins on the wall monitor.
A tweet is sent out.
You sit down at the table and your tablets are 'called' through Lync. 
You collaborate and save stuff. 
You exit the cube, the Lync meeting is exited and a follow-up email is sent.

Aruba handles the device detection.
Octoblu handles the automation of the actions.
Microsoft provides OneDrive and Lync.

Why describe all of this?  Well, for one thing I am kind of excepted about it.  But at the same time, there are lots of moving parts.  And each moving part must play its role.

I had a simple request around the tweet.  Since not everyone provides their twitter handle, can we substitute their first name instead?

Sure, sounds easy enough.
I observed some of the data I had captured.
I thought I was being rather cleaver with my solution and keyed off whether or not there was an '@' in the twittername field.
I tested it, it was great.
I deployed it.

Poo, a new case arose.  The app sending me data is suddenly sending me a twittername that is no more than '@'.  Now I am sending tweets with @ @ @ in them (and hoping that the Twitter spam bots don't kick in and suspend the account).

Suddenly I find myself focusing on my unit tests and the variations that I have seen as well as dreaming up ones that I have not seen but expect to.

In the end to handle this simple request I had 9 conditions to cover the cases of the expected data from the other application.
The golden case where everything is good, and eight cases of other stuff.

Since I use PowerShell to do everything, my JSON looks like this:

$TwitterHandles += @{ “firstname”=”Brian”; "twittername"="@testhandle" }
$TwitterHandles += @{ “firstname”=”Brian”; "twittername"="@" }
$TwitterHandles += @{ “firstname”=”Moheeb”; "twittername"="" }
$TwitterHandles += @{ “firstname”=””; "twittername"="@" }
$TwitterHandles += @{ “firstname”=”Thomas” }
$TwitterHandles += @{ “firstname”=”Joe”; "twittername"=$null }
$TwitterHandles += @{ “firstname”=$null; "twittername"=$null }
$TwitterHandles += @{ “firstname”=”Joe”; "twittername"="null" }
$TwitterHandles += @{ “firstname”="null"; "twittername"="null" }


I had two data fields to cover issues with; twittername always being my first key and the possibility of substituting the firstname.
Now, the resulting code I wrote in JavaScript.  And there is the possibility for 'null' and null.  This is null as a string vs. null as an object / value.  These go right along with missing or blank values.

Suddenly I have something with much better coverage of the possible cases and thus a much better product.
One hour to get the first version and three to work out all the error handling cases.

the end result is a solid product.  But the lesson is to not focus on getting it done, it is to make it solid.

In case anyone want sot see the javascript, here is it;

// Requirement: If there isn't a twitter handle provided, replace with the first name
if(typeof (msg.params.twittername) !== "undefined" && (msg.params.twittername) !== null) {
 if ( (msg.params.twittername).substring(0,1) === "@" && (msg.params.twittername).substring(1) && (msg.params.twittername) !== "null" ){
  return msg;
 } else {
  if ( (msg.params.firstname).substring(0) && (msg.params.firstname) !== "null" ) {
   return {
    params:{
     twittername: msg.params.firstname
    }
   };
  }
 }
} else {
 if(typeof (msg.params.firstname) !== "undefined" && (msg.params.firstname) !== null && (msg.params.firstname) !== "null") {
  return {
   params:{
    twittername: msg.params.firstname
   }
  };
 }
}

Thursday, September 24, 2015

PowerShell to manipulate Skype for Business and Lync converations

A recent project left me playing with the Lync SDK (Skype for Business).

The Skype for Business skin was clad onto the Lync 2013 client.  And thus the Lync 2013 SDK is the one I worked with.
Much of the SDK documentation is centered around writing your own application integration with Lync, event listeners, triggers, etc.  I am just wanting to drive Lync, not write a replacement for it.

Yes, I do know that Office 2016 released (yesterday) but I am not going there just yet.

Lets do some interesting things with Lync:

First - if you want to get started with Lync and PowerShell there are a few blog posts.  I find the automating Lync with PowerShell tutorial from Trevor Sullivan to be the most comprehensive / useful.  I am not going to re-hash what Trevor has already done pretty well.

He walks you though downloading the SDK, installing it, and invoking the 'model' DLL that you need to perform all of the actions.

If you are not a developer, then you still need to install the SDK, for one particular MSI - the redistributable.

In the install folder of the SDK ( C:\Program Files\Microsoft Office\Office15\LyncSDK\Redist ) is the lyncRuntime.msi.  This will give you only the bare minimum DLL that you need to make this all happen.  This would be the thing you package into your application.

Now, allow me to build upon Trevor's foundation.
I am going to launch a 'conversation', then call someone, then start open 'application sharing', then end the conversation.

The big assumption here is that you are logged in to Lync.  I am not going to test for that, MSFT has examples.

# import the Microsoft.Lync.Model.dll
Add-Type -Path 'C:\Program Files\Microsoft Office\Office15\LyncSDK\Assemblies\Desktop\Microsoft.Lync.Model.dll'

# Get the Lync Client SDK automation object
$Automation = [Microsoft.Lync.Model.LyncClient]::GetAutomation()


At this point in time I could go two directions.  I could use the 'Meet Now' feature, or I could build a conversation object the hard way.
What I have learned through experimentation is that the Meet Now sets up quite a few things for you and is thus pretty useful.  I have gone about it the other way and run into sharing problems that I don't run into when using Meet Now.  So I will take advantage of the fact that they have provided this.

# Launch a 'Meet Now' conversation
$meetNow = $Automation.BeginMeetNow({}, 0)
# Get the conversation window to manipulate the conversation.
$conversationWindow = $Automation.EndMeetNow( $meetNow )
# Get the conversation
$conversation = $conversationWindow.Conversation


The first thing that I noticed is that I have something that looks no more than an 'InstantMessage' modality conversation.   That is developer speak for I started a conversation and began a session of the type called instant message.
My experimentation shows that you always have IM in the background, it appears to be the base of the conversation.

Now, I want to create an empty 'Stage' just illustrate the rest.
So I will add the Application Sharing modality.

$Conversation.Modalities['ApplicationSharing'].BeginConnect({}, 0)

The Conversation Window object, there are a few things you can do to it.
Such as, make it full screen.

$conversationWindow.ShowFullScreen('0')

Now, I want to call someone.  And to do that, I add a participant.
To add a participant I do need one piece of information, their SIP URL.  For most organizations this is the email address of the individual, but it does not have to be (that is the caveat).

# add a person only knowing the SIP address (they do not need to be in your contacts list)
$conversation.AddParticipant( $LyncClient.ContactManager.GetContactByUri( "bogusUser@itproctology.com" ) )

# they will receive a Lync Call

You can keep adding folks.  If you forgot who you added, you can look:

$conversation.SelfParticipant # this is you
$conversation.Participants # this is everyone


Now, lets begin to close down this meeting example.

# exit full screen
$conversationWindow.ExitFullScreen() # note the application is left maximized.
# lets resize the window
$conversationWindow.Resize( 300, 300 )

# remove a participant (we only have their SIP address)
$removePeep = $conversation.Participants | where { $_.Contact.Uri -Match "bogusUser@itproctology.com" }


That was a sneaky one liner of me.  Note that I took all of the participants (which is always an array BTW) and I looked for the ContactUri that contained the email of my person to kick off the meeting.

$conversation.RemoveParticipant( $removePeep )
# note, the person you remove receives a notice that they were removed from the conversation.

# End the meeting

$conversation.End()

That is it.  The lifecycle of a Lync meeting from PowerShell

Those objects are powerful.

Say that you already have a meeting running and you want to use PowerShell to find it;
For this we need the Conversation Manager.

$LyncClient = [Microsoft.Lync.Model.LyncClient]::GetClient()
$conversation = $LyncClient.ConversationManager.Conversations


And then find the conversation (as we can have more than one IM conversation at a time).

Now, a few other shortcuts to get you working:

# add IM into IM Window
$Conversation.Modalities['InstantMessage'].BeginSendMessage("Welcome", {}, 0)

# what I can share
$resources = $Conversation.Modalities['ApplicationSharing'].ShareableResources

# share my desktop
$Conversation.Modalities['ApplicationSharing'].BeginShareDesktop( {}, 0)

# share a specific resource
$Conversation.Modalities['ApplicationSharing'].BeginShareResources( $resources[1], {}, 0)

# add voice
$Conversation.Modalities['AudioVideo'].BeginConnect({}, 0)

# remove contect sharing (stop sharing, stage stays present)
$Conversation.Modalities['ApplicationSharing'].BeginDisconnect([Microsoft.Lync.Model.Conversation.ModalityDisconnectReason]::None, {}, 0)

# stop the video call, keep the IM
$conversation.Modalities['AudioVideo'].BeginDisconnect([Microsoft.Lync.Model.Conversation.ModalityDisconnectReason]::None, {}, 0)

# send a thanks for attending IM
$Conversation.Modalities['InstantMessage'].BeginSendMessage("Thanks for attending. Tasks will follow.", {}, 0)

Monday, July 13, 2015

Identifying and running workflows with the Octoblu API and PowerShell

If you are not familiar with Octoblu; it is an IoT messaging system, a protocol translation system, and a message transformer for IoT all rolled into one product.

Since last year I have been spending quite a bit of my time with their systems and platform.
Everything in their system is a device, your user account, a software agent that we demonstrated on the Synergy 2015 stage day 2 keynote, each node that you see in the designer, even that running workflow.  They are all devices and they all have messages bouncing around between them.

One thing that I have come to rely on are their workflows.  I use the flows as a message router / message translator.
By that I mean that I formulate a JSON message and send that to some endpoint (I frequently send a REST message to a trigger using PowerShell).  And the flow will do something with that message - it might change it, filter it, route it to one or many other devices (seen in the flow designer as 'nodes').

All that said, I will probably post about sending and transposing messages later.  It is actually one of the fundamental things that any device does in the IoT world.
I am pretty loose with the concept of what a 'device' is: it can be the Arduino that I have on my desk that runs Microblu, it can be a Node.js application that I run on my workstation, it can be a personal interface to Github (the Github node in Octoblu).  A device is anything that can either send or receive a message.

Back to the title of this post.

I just finished running a long duration test against a 'device' and during this test I wanted to ensure that my workflow remained running.

When you begin to rely on workflows you realize that it is a cloud service and things happen. Sometimes flows get knocked offline.
Over time I have dreamed up a couple approaches to evaluating flows from a 'health' perspective. One of them (my v1) I am using as my base for this post.

This is a really simple approach; make an API call that determines if s flow is running.
If it isn't running, I start it.  Simple as that.

The complexity comes with two different APIs being involved; as there are two different systems of the service at play. 
There is the Octoblu API - this is the Octoblu designer and the GUI and those pretty things that you visually interact with.
And there is the Meshblu API - this guy is the messaging meat of the infrastructure.  He handles routing, security, and devices.  When a flow is run for the first time it becomes instantiated over on Meshblu and becomes a device of the ecosystem.

The code is in my Github Octoblu PowerShell repo here: https://github.com/brianehlert/OctoPosh
The particular script behind this post is: "FlowWatcher.ps1"

Though I have comments in my script allow me to describe a bit more of what is happening.

Invoke-RestMethod -URI ("http://meshblu.octoblu.com/devices/" + $flowId) -Headers $meAuthHeader -Method Get

This is a Meshblu API call to fetch the properties of an individual device.  Note the $flowId GUID string in the URI path.  Leave that GUID out and you get back an array of all of the devices that you 'own'.

Invoke-RestMethod -URI ("https://app.octoblu.com/api/flows/" + $flowId) -Headers $meAuthHeader -Method Get

This is an Octoblu API call to fetch an individual flow / workflow.  Just as happens if you open one in the designer, you get all of its properties.

Invoke-RestMethod -URI ("https://app.octoblu.com/api/flows/" + $flowId + "/instance") -Headers $meAuthHeader -Method Post

This is another Octoblu API call to start a flow.  What happens is that a flow device instance gets instantiated in Meshblu (this way it can receive messages).  This is why I call the Meshblu API to see if it is 'running'.

Invoke-RestMethod -URI ("https://app.octoblu.com/api/flows/" + $flowId + "/instance") -Headers $meAuthHeader -Method Delete

This is a Meshblu API call to stop flow.  What it does is delete the running instance of the device.  If you query this particular device in Meshblu (after you have run it once) you will find it in Meshblu, but it may not be running.  If it is running, it is a little process within the infrastructure, when not running it is still defined as a device.

I hope you find the script and this little API tutorial to be useful.

Thursday, July 9, 2015

Indexing Format-Table output

Today, I had the crazy idea of outputting an array in PowerShell as a table, and I wanted to show the index of each array value.

In laymen's terms: I wanted my table output to be line numbered.  And I wanted to line numbers to correspond to the position in the array.

Why? because I didn't want the user to type in a name string or a GUID string that they might typo, they could simply enter the index of the item(s).
Trying to solve potential problems upfront, without a bunch of error handling code.

I started out with a PowerShell array that looked something like this:

PS\> $allFlows | ft name, flowid -AutoSize

name                     flowId
----                     ------
bjeDemoFlow_working      70bd3881-8224-11e4-8019-f97967ce66a8
bje_cmdblu               3e155fe0-dc9a-11e4-9dfc-f7587e2f6b74
Pulser_WorkerFlow_Sample f945f94f-fb33-4181-864d-042548497270
Flow d59ae1e8            d59ae1e8-0220-4fd2-b40f-fba971c9cf42
bjeConnectTheDots.io     204b5897-2182-4aef-84fe-1251f1d4943b
StageFlow_1              796d0ff4-94d6-4d1a-b580-f83ab98c7e15
Flow f26aab2f            f26aab2f-783b-4c09-b1fc-9e6433e8ab37
Flow c983c204            c983c204-5a87-4947-9bd2-435ac727908a
v2VDA Test               ba5f77af-98d1-4651-8c35-c502a72ccea8
Demo_WorkerFlow          e7efdac4-663d-4fb6-9b29-3a13aac5fb97


Now for the strange part.  How do I number the lines in a way that they correspond to each items position in the array?

Search did not fail me today, but it took a bit of effort to discover an answer in StackOverflow from PowerShell MVP Keith Hill.
And, also looking at Get-Help Format-Table -Examples and realizing that there is an 'expression' option to calculate the value of a field in the table output.

PS\> $allFlows | ft @{Label="number"; Expression={ [array]::IndexOf($allFlows, $_) }}, name, flowid -AutoSize

number name                     flowId
------ ----                     ------
0      bjeDemoFlow_working      70bd3881-8224-11e4-8019-f97967ce66a8
1      bje_cmdblu               3e155fe0-dc9a-11e4-9dfc-f7587e2f6b74
2      Pulser_WorkerFlow_Sample f945f94f-fb33-4181-864d-042548497270
3      Flow d59ae1e8            d59ae1e8-0220-4fd2-b40f-fba971c9cf42
4      bjeConnectTheDots.io     204b5897-2182-4aef-84fe-1251f1d4943b
5      StageFlow_1              796d0ff4-94d6-4d1a-b580-f83ab98c7e15
6      Flow f26aab2f            f26aab2f-783b-4c09-b1fc-9e6433e8ab37
7      Flow c983c204            c983c204-5a87-4947-9bd2-435ac727908a
8      v2VDA Test               ba5f77af-98d1-4651-8c35-c502a72ccea8
9      Demo_WorkerFlow          e7efdac4-663d-4fb6-9b29-3a13aac5fb97


The values for the column are defined as a hashtable @{}
With the Label of the column and the Expression that defines the value.

Pretty nifty new trick to add to my repertoire.












 
 

Friday, May 1, 2015

Further automating GoToMeeting on a Windows client

To continue to build on my previous post I decided to add a bit of id10t proofing to my automation script.

The only thing that the script does not do is logon the user (I mean, who really wants to handle (secure) user credentials in the first place).

This is here for my benefit, but I am sure that this can be useful to someone else.  There is nothing here that I did not discover through internet search or my own discovery.

I don't register an event monitor for a simple reason, I cannot guarantee that the execution of this program has admin rights.  Admin access on the local computer is required to register for an event, though it would be nice for a user to be able to register for user mode process events.

Enjoy!

<#
.SYNOPSIS
    This will install the full G2M client for hosting meetings if it is not already installed prior to joining the meeting.
.PARAMETERS
    $g2mId - the meeting ID that will be joined. This can be any g2m ID, the user will be 'joining' an existing meeting (theirs or someone else's).
    $g2mKill - if there is a G2M already running that will be killed and the passed G2M will be joined.
.AUTHOR
    Brian Ehlert, Citrix Labs, Redmond, WA
#>


function startG2m
{

Param(
    [parameter(Mandatory = $false)]
    [ValidateNotNullOrEmpty()]
    [string]$g2mId,
    [parameter(Mandatory = $false)]
    [boolean]$g2mKill = $false
)

    # finds the path of g2mstart.exe
    # each version is in its own folder so you have to find the latest / most recent version
    $gtmFolder = Get-ChildItem -Path $env:LOCALAPPDATA\Citrix\GotoMeeting -ErrorAction SilentlyContinue | Sort-Object -Property Name -Descending | Select-Object -First 1

    if ( !($gtmFolder) ) {
        "G2M is _not_ installed. Installing the hosting client."
       
        # Install the GTM client
        Start-Process "https://global.gotomeeting.com/meeting/host"

        Start-Sleep -Seconds 2
        # close the IE tab that was opened
        $ie = (New-Object -COM "Shell.Application").Windows() | where { $_.Name -eq "Internet Explorer" }

        foreach ($tab in $ie) {
            if ( $tab.LocationURL -match "download.citrixonline.com" ) {
                do {
                    Start-Sleep -Seconds 1
                } until ( $tab.Busy -eq $false )
                $tab.Quit()
            }
        }

        # wait for the client logon prompt
        Do { Start-Sleep -Seconds 2 } until ( Get-Process -Name "g2mlauncher" -ErrorAction SilentlyContinue )

        startG2m -g2mId $g2mId
    } else {
        # is there an existing G2M that needs to be killed?
        # if we reconnect to the same meeting too quickly we will have ourself as an orphaned attendee.
        if ($g2mKill) {
            if ((Get-Process -Name "g2mui" -ErrorAction SilentlyContinue)) {
                "Killing the running G2M"
                Get-Process -Name "g2mui" | Stop-Process -Force
                Do { Start-Sleep -Seconds 2 } until ((Get-Process -Name g2mlauncher -ErrorAction SilentlyContinue).Handles -lt 500)
            } else {"The user was not joined to a G2M"}
        }

        "G2M is installed, using the installed client"
        # build the path
        $g2mstartPath = $gtmFolder.FullName + "\g2mstart.exe"

        # Define the arguments - double quotes is important for g2mstart.exe
        $g2mArgs = ("'/Action Join' '/MeetingID $g2mId'" ).Replace("'",'"')

        # is there a G2M video conference running?  We will collide if there is.
        if (!(Get-Process -Name "g2*conference")) {
            if ( $g2mId ){
                "Joining the meeting"
                Start-Process -FilePath $g2mstartPath -ArgumentList $g2mArgs
            } else { "No G2M ID was provided" }
        } else { "A G2M is already running" }
    }
}


#Example
startG2m -g2mId 000000000 -g2mKill $true
Start-Sleep -Seconds 5  # wait for the conference to initialize
$process = Get-Process -Name "g2*conference"
Wait-Process -InputObject $process # wait for the person to end the conference
# Do something else
"boo!"

Tuesday, April 28, 2015

PowerShell launching GoToMeeting on Windows

It isn't every day that you need to execute GUI application commands via command line. 
After all there are some GUI applications that simply don't design for it and don't document it. 
It really is not a use case that they expect.

GoToMeeting is just one of those applications.  It is never anticipated that a person might want to launch a session via a command line.

Well, I recently had such a case.  And I have two different ways to handle this.

First, a little bit about the application. 
GoToMeeting is a user mode application that is 100% in a user's profile.  It is web based, and has a web based launcher that always delivers the latest and greatest client.  The client side application is not found under %ProgramFiles%.

Launching / Joining a Meeting:
Method 1 (the modern way):

Start-Process http://www.gotomeeting.com/join/$g2mId

Method 2 (the legacy way):
This method was the most prevalent result when I searched.  Send arguments to g2mstart.exe.
However, this is also the most problematic.  GoToMeeting updates its client pretty frequently, and each client is in a new folder, so if you want the latest client you have to do a bit of discovery and you must format the string properly.

# each version is in its own folder so you have to find the latest / most recent version
$gtmFolder = Get-ChildItem -Path $env:LOCALAPPDATA\Citrix\GotoMeeting | Sort-Object -Property Name -Descending | Select-Object -First 1

# build the path
$g2mstartPath = $gtmFolder.FullName + "\g2mstart.exe"

# Define the arguments - double quotes is important for g2mstart.exe
$g2mArgs = ("'/Action Join' '/MeetingID $g2mId'" ).Replace("'",'"')

# start the meeting
Start-Process -FilePath $g2mstartPath -ArgumentList $g2mArgs


It would be improper of me not to focus on the modern way of doing this.  The way that is expected.  However, the one thing that doing it that way will accomplish is that the client might be forced into an update.  If you don't want your client updated, but instead want a nice seamless join, you might want to use the legacy method.

Allow me to present the modern and legacy functions:


function startG2m {
Param(
 [string]$g2mId
)

  # start the meeting
  Start-Process http://www.gotomeeting.com/join/$g2mId
  Start-Sleep -Seconds 2

  # close the IE tab that was opened
  $ie = (New-Object -COM "Shell.Application").Windows() | where { $_.Name -eq "Internet Explorer" }

  foreach ($tab in $ie) {
    if ( $tab.LocationURL -match "gotomeeting.com" ) {
      do { 
Start-Sleep -Seconds 1 } until ( $tab.Busy -eq $false )
      $tab.Quit()
    }

  }
}



function startG2mLegacy {

Param(
 [string]$g2mId
)

  # finds the path of g2mstart.exe
  # each version is in its own folder so you have to find the latest / most recent version

  $gtmFolder = Get-ChildItem -Path $env:LOCALAPPDATA\Citrix\GotoMeeting | Sort-Object -Property Name -Descending | Select-Object -First 1

  # build the path
  $g2mstartPath = $gtmFolder.FullName + "\g2mstart.exe"

  # Define the arguments - double quotes is important for g2mstart.exe
  $g2mArgs = ("'/Action Join' '/MeetingID $g2mId'" ).Replace("'",'"')

  # start the meeting
  Start-Process -FilePath $g2mstartPath -ArgumentList $g2mArgs

}


Now, using these two functions is identical.

startG2m $g2mId

But, being a person who does test I always like a bit of error handling, I hate popup dialogs.  And I especially hate dialogs if they interrupt my nice automation - a real buzz killer.

Here I have two checks - 1. is there an existing meeting that I need to kill to connect to a new meeting ("there can be only one"  - the Highlander) and 2. Don't start it if one is running.

# is there an existing G2M that we need to kill?
# Note - if we reconnect to the same meeting too quickly we will have ourself as an orphaned attendee.
if ($g2mKill) {
  if ((Get-Process -Name "g2mui" -ErrorAction SilentlyContinue)) {
    "Killing the running G2M"
    Get-Process -Name "g2mui" | Stop-Process -Force
    Do { Start-Sleep -Seconds 2 } until ((Get-Process -Name g2mlauncher).Handles -lt 500)
  } else {"The user was not joined to a G2M"}
}

# is there a G2M video conference running? We will collide if there is.
if (!(Get-Process -Name "g2*conference")) {
  if ( $g2mId ){

    # Start the G2M
    startG2m -g2mId $g2mId
  } else { "No G2M ID was provided" }
} else { "A G2M is already running" }


Wednesday, October 8, 2014

XenDesktop DSC resource and the Azure DSC VM Extension

After all of the previous blog posts, I thought that I would climax with a few real examples of using the DSC resource for XenDesktop.

Earlier this year (just a few++ weeks ago) Microsoft released the VM extensions for Virtual Machines.  This is the IaaS style VM role.  The VM Extensions are small modules that you can inject into your VM and you can interface with them.  The simplest way to think of it is they are purpose built agents.  You can configure them on provisioning, but also nifty is that you can update the configuration of an extension after deployment and do something else.

There is a script extension that can be used to download and execute any script(s) inside of your VM.  Handy for performing a number of things. You can use this to drive DSC if you like.
After that the DSC extension was released.  This one is purpose built just for DSC and the one this post will be focusing on.

I will warn you, I am going to expose a few warts of the process as I do this, just because the extension is built to support DSC and only the DSC packages.  And this process requires external media - yes, the media could be bundled into the DSC resource (the only workaround to this process at the moment), but that would make the resource really fat.  So, why not continue to think of it as two problems.

One thing - the DSC provider for XenDesktop expects media to be on the machine where it runs or a DVD attached ISO.  So a ZIP or ISO (DVD attached or downloaded to the machine) or folder.  This way there is no requirement to save credentials for connecting to some share or other store.

Now, let get everything set up.  (I am experimenting with a slightly different writing format here, so you will have to let me know if it works for you)

First of all, I am going to assume that you are sitting at your 'configuration computer' - that management computer that you use that has all of the consoles and what not installed.  In this case it is where you build all of your configurations that you later push to machines or place on your pull server.  Your configuration computer needs the XenDesktop resource module installed under the path "%ProgramFiles%\WindowsPowerShell\Modules" so a later cmdlet for the DSC script provider can automagically pick it up and bundle it for you.

Begin by connecting to your Azure subscription and set the storage account you will be using ( Set-AzureStorageAccount -StorageAccountName "YourCoolStorageAccount" )

Then upload the XenDesktop media.  ( the media is created from the ISO, simply ZIP the contents of the ISO - don't add any folders into the path)
Be sure that your container security is set to public blob (not public container) since we don't want folks discovering it.

For a later step you will need the URI to the blob that you just uploaded.

Now, we need to define the configuration (the DSC one) that will be applied to the VM.

For that I created a PowerShell script that accepts two parameters; the URI to the media and the role to be installed.

The DSC extension will run this and then apply the configuration.

Now that the configuration script exists, this must be packaged up, with the module, for the Azure DSC extension to use.  I saved mine with the name "XenDesktopInAzure.ps1".

The Azure PowerShell cmdlets have created a cmdlet just for this action; Publish-AzureVMDscConfiguration

After running the Publish-AzureVMDscConfiguration cmdlet, go check out your Azure management portal and look into the container and you will find a ZIP archive with a name that matches your script.  What the Public- command does is package the script and the modules that are used into the ZIP, then uploads them to Azure for you.

Now, define the VM, so that can be created.

First needed is an Azure VM Image - an 'image' is a virtual disk that is installed with an OS and prepared with sysprep and registered with Azure as an image - to the management platform, this means that it can specialize the OS on provisioning through mini-setup and the use of an unattended answer file.
Moving forward to the next step of building the VM configuration.

First, begin with a base VM configuration.

Then add the provisioning configuration ( these are the specialization settings ).
Then configure the Azure DSC VM extension.

Then create the VM.  Azure and the VM extension take care of processing the configuration script, and the configuration script downloads the ZIP, unpacks it, and installs the role.



One really cool thing about DSC is that you can keep applying configurations.  The last applied settings to a specific thing win, configurations are not undone when a new one is added, simply the changes defined in the new configuration are applied.  So, if you have some management layer, it can apply configuration after configuration if it so wanted to, or change a configuration over time to modify something.



As an option for delivering media, you can use a data disk with the XenDesktop media within it.  Then you can attach that to a new VM and have DSC mount the disk (rather, make sure it is mounted at a specific drive letter) and then perform the installation.

If you are using SCVMM, you can have an ISO attached to the VM as part of the template.  You could even use DSC to map a drive if that is what fits for your environment.  They are all possibilities.

Have fun! And please, send feedback!

Monday, October 6, 2014

Using the XenDesktop DSC resource

In my last article I covered using the built-in desired state configuration (DSC) resources to stand up a Citrix License server.  All but one of the resources I used shipped in the box with Server 2012 R2 - and you could argue that I really didn't have to use the custom resource to fetch and install my license file.

I used the package resource to install the Citrix License server. 

The package resource works great for the License Server, which is a really quick and simple install.  But what do you do when you have an installer that requires reboots mid-stream?  Or even multiple reboots? 

Some of you who have installed XenApp or XenDesktop over the years know that this takes extra time and you have to follow your checklist or the wizard to make sure you didn't miss a step.  What if you didn't need to do that?  Or what if we could greatly simplify the entire process?

Here is an example I think you will like.

Recently released is a Technology Preview of a desired state configuration resource for XenDesktop.  You can find it here: http://www.citrix.com/go/xendesktop-for-the-private-cloud.html

Follow the admin guide and place the module in the PowerShell path on your target (and the machine where you create configurations) and move forward.

Since I will be using this in upcoming examples, lets give it a quick description.




This brings together a few of the previous articles.

Lines 9 - 12 coupled with line 47 sets the local configuration manager (LCM) to handle reboots on its own.

Lines 15 - 20 creates my unzip and logging path

Lines 24 - 30 unzips my media.  I know what the name of my media is and I expect that media to be delivered to the same path where this script is being run by some other agent or process - such as an external process that downloads the media plus this script to the same path and then runs this script.

Lines 33 - 38 call the XenDesktop resource and install one of the roles defined.

If the role installation sets that the system requires a reboot, the LCM handles that.  On reboot it processes the configuration again, until the XenDesktop resource returns 'true' for ensure being set to 'present'.

For the Controller this is generally one reboot, for a session host or VDA tis could be two reboots.  The great thing for me is that it is totally hands off.  DevOps in the XenDesktop world.

Personally, I hope that you check this out, and I am looking for feedback on where this needs to go next and if it is useful to you.  So please, speak up in comments, in the forum, or complete the survey.

Next - lets show this all in action in some real use cases.

Tuesday, September 30, 2014

Using the native DSC resources

In my previous posts the focus was on giving some background into how desired state configuration DSC works, some ideas about how to use it, and some details around a very simple example.

Here I am going to walkthrough a configuration that uses a number of the built in DSC resources to apply a configuration.

First, I want to back up a bit and mention a concept.  If you read through many of the blog posts and TechNet documents out there all of the examples you see you could easily describe as being installation focused.  Or only making changes to the system that one would do when installing something.  And this observation is correct.  DSC is still in that v1 state at this writing which means that folks are getting used to it, using it, extending it.  And frankly talking about installation actions is relatively easy. 

One thing I want to mention now is that anyone can build a Custom Resource.  And if you want to configure an application, this is the way to go.  Put all of your complex logic into that custom resource.  Or, wait for the software vendor to write that custom resource so you can use it.  And you may need to ask them to do that for you to get the ball rolling.  There is nothing that says that DSC cannot be used to configure the applications that it also installs in a previous step.  We will get closer to that later on.

Back to this example, installing a Citrix License Server using DSC resources.

Before we get into my example I want to mention a couple things:

  1. In my setup I am using the full XenDesktop media ISO as a ZIP archive and I am hosing it on an HTTP endpoint (IIS Server).  This is an internally hosted, isolated, and unsecured endpoint - it is strictly an example to demonstrate different resources and possibilities.  In other words, please learn from the example but please "don't do this at home". 
  2. Also,  I am not demonstrating any commands that are not already documented in Citrix eDocs nor the DSC documentation in TechNet.  You need to read those sources for the definitive and current documentation.

Here is the configuration script sample:



Lets start to work through this example.

On line 3 is something new; Import-DscResource.  This is now modules are invoked when they are not shipped as part of the operating system.  Prior to being able to apply this configuration the module xPSDesiredStateConfiguration must be in the PowerShell path.  If you observe the behavior of a Pull configuration you will notice that it uses the path "%programfiles%\WindowsPowerShell\Modules" - and because of that I tend to use that one myself.  More on custom resources later.

On lines 7 - 12 you see the [File]citrixFolder resource that I have been showing in the previous articles.

On lines 14 - 31 is something new as well.  The Script resource. 

This is a utility resource that fills a gap when there is no other resource available to perform your actions.  When you use the Script resource you essentially write a mini custom resource - it has all the same base requirements of a custom resource provider. 

In this case I am using the web client to download the XenDesktop media to the %programdata% path I defined with [File]citrixFolder.  You might also notice that there is a dependency on that previous resource to ensure that the path exists prior to downloading.

Lines 33 - 39 use the Archive resource.  Here I define the path where I know the ZIP exists (previous dependency), and the destination I want it extracted to.

If you run the -Verbose switch when applying this configuration you will notice some interesting behavior with this provider.  The archive provider actually opens the ZIP, reads every file and tests the destination for the existence of the file.  If a file exists, it is not extracted, if it does not exist it is extracted.  This is just a bit of insight into the thinking around how desired state works and what it means to apply a configuration.

Lines 41 - 50 use the Package resource.  This resource is used to install or uninstall packages.  It is centric to MSI packages but it can also be used with EXE packages.  The installer must support silent installation.  Also, as you can see I left the ProductId empty - that is a property of MSI packages so I had to define it this way.

Lines 52 - 57 are the reason for the Import-DscResource.  Within that module is the provider xRemoteFile.  This resource allows me to use a URI as the source.  I defined the source file and my destination - and this places my license file right where my license server default path is.  Ready to go!

Why didn't I use this in place of the script extension?  Good question.  It is because the file I am downloading using the script resource is too large and the download fails at 1.7 Gb in a very reliable way (it is actually a very old bug).

That is it.  The hardest part is getting the infrastructure working to get the media and files delivered.

But quite honestly, MSFT is working on that problem.  Have you heard of OneGet or PSGet?  OneGet is all about packages, packages that could be used by DSC.  PSGet is about PowerShell modules.  And, you can set up your own internal version if you don't trust the public repositories.  But the nifty thing is this; ISVs can publish their packages to OneGet - and then their customer just points to it and before you know it that application is downloaded and installed.  Really nifty delivery method - almost like yum for Windows.

Friday, September 26, 2014

The next step for DSC configurations

Just to recap, this is a series regarding Desired State Configuration which shipped with Windows Management Framework v4 (Server 2012 R2 / Windows 8.1).  There are some references in my first article if you want to get deeper, and there is always TechNet and MSDN documentation.

In this article I am going to expand on my simple example from the last article.  Step it up a notch if you will.

The first thing I am going to cover is the DependsOn property.

This is why each of your declared resources has a name.

Lets consider the following sample:



The Log resource DependsOn the File resource citrixFolder.  What this means is that the File citrixFolder must complete or else the Log afterCitrixFolder will not be attempted.  Another way to say this is that the test for citrixFolder must return True.

This allows a chain of dependencies to be defined.  Defining them here, the configuration author must know about the dependencies and declare them.  Another option is that the resource provider itself is aware of dependencies and enforces them, but that is definitely an advanced topic.

In the last article I had mentioned that the Local Configuration Manager configuration could be changed.  This to is a configuration, and a special command.

Here is my scenario, I have a package installation that DSC is handling for me.  This is a complex installation and it requires two reboots for everything to be installed properly.  I want DSC to handle the rebooting, I don't want to have to setup jobs and start-up commands and the like as in the past.

For this I use the following example;


The first thing to notice is lines 6 through 10.  This is a special resource; localconfigurationmanager.  It supports modifying the properties of the LCM itself.  In this case the reboot behavior is false by default and I want to set that.

After I generate the MOF document, there will be two documents in the .\sample path.  The localhost.mof as before and a localhost.meta.mof that defines the behavior of the LCM.  Set-DscLocalConfiguraitonManager applies the LCM configuration and then Start-DscConfiguration applies the remainder.

If you have done any blog reading of DSC you would most likely have run across the 'Pull' model (and realize that I have been showing the 'push' model) of applying and managing configurations.

I bring this up now just to mention that the Pull model requires the LCM to be configured this way; as shown here:


In this sample I am setting the GUID that matches the configuration of this machine, I am telling it that it is using WebDownloadManager to download its configuration, the URL of my DSC Pull Server, that it will only apply the configuration and then stop, that it will reboot, and I set the frequency down to the minimum since I am impatient.

Just like above, This is a modification of the Local Configuration Manager on the target machine.

The Pull model is pretty handy, as there is simply one web endpoint where configurations call home to and then fetch their configuration and apply it.  If I change the configuration, I change it here and when the node performs its refresh it will look to see if the configuration changed and if it did the new configuration is downloaded and applied.

Pretty slick feature.  But I have to admit, keeping a bunch of GUIDs straight is not the easiest thing.  In this mode each configuration is the GUID identified by the ConfigurationID.  And you have to make sure you give the right configuration ID to the right VM.

Optimally, you set up an array and simply randomly assign one configuration to a machine out of a bunch of machines and wait for the magic to happen.  That is really where that model works.

If you really want to get into all of the possibilities of applying configurations to machines there is a good blog article that describes the options when you want your machine to automatically configure on boot up with DSC.  There are some interesting options in there such as

  • using mini-setup and the unattend.xml to set a task to run a configuration script on boot.
  • drop a pending.mof in the path %systemdrive%\Windows\System32\Configuration (mount the vhd and copy the file in) that the LCM will automatically process on boot
  • inject a meta-configuration (the configuration of the LCM) to download its configuration document

Not mentioned is that you can use and agent in the VM to execute a script, set a MOF, or trigger the LCM in a number of combinations.  And there is also remote applying a configuration as this is what Start-DscConfiguration uses by default using the -ComputerName of a remote machine (you have to be administrator).

Using SCVMM Service Templates the DSC configuration script would be the 'script application package' being executed by the SCVMM agent.  And the model is similar for a Windows Azure Pack Gallery Image.  If you are deploying to Azure you can use the VM DSC Extension or the VM Script Extension - both through the Azure API.

So, as you can see, the flexibility is all over the place.