Not wanting to add to my already bursting email inbox and finding the need for a more immediate mobile notification of scripted events I find myself looking at https://boxcar.io and their end-user API .

The API provides an example on how to use the service with cURL so as before I will be converting this simple format to use the PowerShell Invoke-WebRequest cmdlet and wrap this into an advanced function.

Setup
•    Download the Boxcar iOS app
•    Get your Access Token and replace the value for the $user_credentials variable in the Param section of the function  – How to get the Token from the client app
•    Like all PowerShell functions you will need to run the code at least once and you can call it as many times as required for the session.

The best way to copy the code from a WordPress blog such as this one is to double click in the below window and then copy, this usually preserves the formatting.

function Send-BoxcarPush  {
<#
.SYNOPSIS
A function to send Boxcar Push messages.
.DESCRIPTION
An example of using PowerShell to send Universal Push Notification messages. Typically the target device is a mobile running iOS (https://boxcar.io/client) or Andriod.
.PARAMETER notificationTitle
Message Title/Subject. 140 Character Maximum.
.PARAMETER notificationLongMessage
Message body text. 1000 Character Maximum.
.PARAMETER notificationSound
Notification Sound played on receiving device. Default is ‘bird-1’, see the Available sounds list for options - https://boxcar.uservoice.com/knowledgebase/articles/306788-how-to-send-your-boxcar-account-a-notification
.PARAMETER hostURI
Default is usually fine.
.PARAMETER user_credentials
Boxcar Access Token. Its recommended you change this value in the Param section of this function else it will need to be specified each time. The access token is available from the general "Settings" screen of Boxcar Client app.
.EXAMPLE
Send-BoxcarPush -notificationTitle "Test Title" -notificationLongMessage "Body message text"
.NOTES
Author: John Milner
Blog  : https://jfrmilner.wordpress.com
File Name: Send-BoxcarPush.ps1
Author: jfrmilner
Email: jfrmilner@googlemail.com
Requires: Powershell v4 (May work on older versions but untested)
Legal: This script is provided "AS IS" with no warranties or guarantees, and confers no rights. You may use, modify, reproduce, and distribute this script file in any way provided that you agree to give the original author credit.
Version: v1.0 - 2014 March 1st - First Version
Version: v1.1 - 2014 March 2nd - Added URL Encoding
.LINK
https://jfrmilner.wordpress.com/2014/03/01/powershell-pus…ered-by-boxcar/
#>
Param(
[String]
[parameter(Mandatory=$true)]
[ValidateLength(1,140)]
$notificationTitle = "test"
,
[String]
[parameter(Mandatory=$true)]
[ValidateLength(1,1000)] #Max is 4kb so 1000 is playing safe.
$notificationLongMessage = "text here"
,
[String]
$notificationSound = 'bird-1'
,
[String]
$hostURI = 'https://new.boxcar.io/api/notifications' #HOST: This is the server to use to send HTTPS API calls.
,
[String]
$user_credentials = 'Put Your Access Token Here' #Access Token. Change this value to your own here or specify here.
)

BEGIN{
Add-Type -AssemblyName System.Web
}#begin
PROCESS{

try
{
$message = Invoke-WebRequest -Uri $hostURI -Method POST -Body "user_credentials=$($user_credentials)&notification[title]=$([System.Web.HttpUtility]::UrlEncode($notificationTitle))&notification[long_message]=$([System.Web.HttpUtility]::UrlEncode($notificationLongMessage))&notification[sound]=$($notificationSound)"
if ($message.StatusCode -eq 201) {
"Message Sent:"
$message.Content | ConvertFrom-Json
}
}

catch [System.Net.WebException]
{
Write-Host  -ForegroundColor Red $_.Exception.Message
switch -regex ($_.Exception.Message)
{
"401" {Write-Host  -ForegroundColor Red "Failure: Check Access Token"}
"404" {Write-Host  -ForegroundColor Red "Failure: No associated device"}
"422" {Write-Host  -ForegroundColor Red "Failure: Unprocessable Entity - All non UTF-8 encoding are rejected"}
default {Write-Host  -ForegroundColor Red $_.Exception.Message}
}

}

finally
{

}
}#process
END{}#end

}

Example

BoxcarPowerShellExample

BoxCariOSExample

Boxcar deliver a great service which is free for 200 pushes per minute and its fast, very fast.
Boxcar notifications can use 20+ different sounds which I’m starting to find quite useful, for example you can have different scripts use different sounds which I just listen out for and this saves me having to look at the phone. I’m also thinking I could use different sounds for different levels of importance.

As always thank you for reading and if you found this post useful please share and/or leave a comment.

Regards, jfrmilner


In this post I’m going to share a script I wrote that speeds up the creation of Cisco MDS 9000 series SAN switch configurations. If like me you’re in the business of adding Cisco UCS Blades in bulk you will know that copying and pasting large amounts of wwpn’s and zoning can be prone to errors – let alone time consuming. Thankfully Cisco released the Cisco PowerTool pack for PowerShell for managing UCS environments; this allows easy access to extract all the necessary information needed to create our configurations quickly and consistently.

The SAN that was used to demo this script contains two Cisco MDS switches with two connections a piece to SPs on an EMC VNX5300.

This script should be treated as an example rather than a script that is generic enough to be run in any environment. In the below script you will notice three areas that have “#User to change as needed” comments, here you will see that I have unique values specific to my environment that will need to be edited. These values include my VSAN numbering, Zoneset naming and some datacentre location information.

First you will need to import the PowerShell UCS module and then connect to your UCS environment:

Import-Module CiscoUCSPS
Connect-Ucs <UCSIP> -Credential (Get-Credential)

Upon running the script you will be prompted for the serviceProfilePrefix which I use to filter Service Profile Names, in my example I will use the text “PDC” which represents a collection of VMware vCloud Director Provider vDC Blades.

Note: To copy the code please double click within the code box.

<#
.NOTES
Author: John Milner aka jfrmilner
Blog  : https://jfrmilner.wordpress.com
Post  : http://wp.me/pFqJZ-6y
Requires: Powershell + Cisco UCS PowerTool Pack
Legal: This script is provided "AS IS" with no warranties or guarantees, and confers no rights. You may use, modify, reproduce, and distribute this script file in any way provided that you agree to give the original author credit.
Version: v1.0 - 27 Oct 2013
#>
param ( [Parameter(Mandatory=$true)] [System.String]$serviceProfilePrefix )

$vSANs = 3801, 3802 #User to change as needed

#Clear Host Screen
Clear-Host

#Collect all Initiators
$initiators =  Get-UcsWwnInitiator | ? { $_.Assigned -eq "yes" } | Sort-Object -Property AssignedToDn
foreach ( $initiator in $initiators ) {
$split = $initiator.AssignedToDn -split "/"
Add-Member -InputObject $initiator -Name ServiceProfile -MemberType NoteProperty -Value ($Split[1] -replace "^ls-") -Force
Add-Member -InputObject $initiator -Name vHBA -MemberType NoteProperty -Value "vHBA$($split[2].ToCharArray()[-1])" -Force
}

#Create Service Profile List
$serviceProfiles = $initiators | Sort-Object serviceprofile | Select-Object serviceprofile -Unique
#Filter List with serviceProfilePrefix param
$serviceProfiles = $serviceProfiles | ? { $_.serviceProfile -match $serviceProfilePrefix } | % { $_.serviceprofile }

$vHBAs = "vHBA0","vHBA1"

foreach ( $vSAN in $vSANs ) {

switch ($vSAN) {
3801 {"!D10 Config" ; $vHBANum = $vHBAs[0] ; $zoneSetName = "D11_MDS01" ; $SPA = "SPA0" ; $SPB = "SPB1" ; [int]$dataHall = 1 } #User to change as needed
3802 {"!H18 Config" ; $vHBANum = $vHBAs[1] ; $zoneSetName = "H18_MDS02" ; $SPA = "SPA1" ; $SPB = "SPB0" ; [int]$dataHall = 2 } #User to change as needed
}
foreach ( $serviceProfile in $serviceProfiles ) {
$vHBA = $initiators | ? { ($_.serviceProfile -eq $serviceProfile) -and ($_.vHBA -eq $vHBANum)}

"fcalias name ESX_DH$($dataHall)_$($serviceProfile)_$($vHBA.vHBA) vsan $($vSAN)"
"member pwwn $(($vHBA.Rn).tolower())"
}
foreach ( $serviceProfile in $serviceProfiles ) {
"zone name Z_ESX_DH$($dataHall)_$($serviceProfile)_$($vHBANum)_DH$($dataHall)_VNX5300 vsan $($vSAN)"
"member fcalias DH$($dataHall)_VNX5300_$($SPA)"
"member fcalias DH$($dataHall)_VNX5300_$($SPB)"
"member fcalias ESX_DH$($dataHall)_$($name)_$($vHBANum)"
}
"zoneset name ZS_NDC1_$($zoneSetName)_SAN_JFRMILNER_NET vsan $($vSAN)"
foreach ( $serviceProfile in $serviceProfiles ) {
"member Z_ESX_DH$($dataHall)_$($serviceProfile)_$($vHBANum)_DH$($dataHall)_VNX5300"
}

}

The output of the script will be presented to the console, here is an example:

MDS Config

As you can see in the above output the script has created fcaliases for each of the newly provisioned PDC Service Profile HBAs, created Zones and added these to the Zoneset for both my Switches.

Additionally this script can be easily modified to do bulk removals as it’s just a matter of prefixing some of the configuration lines with “no” for example “no fcalias name” and “no zone name”, as this has potential of causing an APD situation I will not be providing any example of this.

I hope you find this script useful and that it saves you as much time and reduces human error incidents as it has for me. As always please add a comments below and thank you for reading.

Regards,

jfrmilner


This post will detail how I created a simple home automation project to control multiple power outlets using an Arduino Mega microcontroller.

Project highlights:
•    Reduce the amount of systems left on standby and ultimately reduce the amount of wasted energy.
•    Remotely control the power state of multiple devices.
•    Power on and off a media server by using the Power button on the front of the computer.
•    Control a collection of radio frequency (RF) devices, including single sockets and power strips.
•    Control a couple of Power Distribution Unit’s (PDU).
•    Collect and present power state information via a web page that is iDevice mobile friendly.
•    Control all the above using a single Arduino Mega with an Arduino Wiznet Ethernet Shield.

The ability to remotely manage the power states of a computer or external device over the internet can be very expensive using traditional off the shelf products, in this post I’m going to show you how I achieved this using a single Arduino. I use wireless RF and IP controlled devices for all mains power related switching so there is no risk of high voltage shocks.
This project could be recreated exactly by others but I believe that it’s more likely that people will pick and choose areas of this project and implement these into their own. The code has been made available and is fairly simple to follow due to the use of functions and comments.

As this is a physical computing project I decided to do a quick overview video to accompany this post.

This video is best viewed in 1080p HD.

Bill of materials:

# Name Price Shop
1 Arduino Mega £20 Google/eBay
2 433 Mhz Transmitter and Receiver £3 eBay: search for “Arduino 433″ or “RF Link kit”
3 Energenie Trailing Gang with Four Radio Controlled Surge Protected Sockets £20 https://energenie4u.co.uk www.amazon.co.uk
4 Opengear IP PDU ? http://www.digipower.com.tw/PDU/BravoPDUswitched.htm
5 Breadboard and a few jumper cables Google/eBay
6 2N2222 NPN bipolar junction transistor £1 http://en.wikipedia.org/wiki/2N2222

Step One – Directly connected PC
I thought it would be interesting to use a remote method to power up and shutdown a PC by directly connecting to the power button. I opened the case and popped the power switch out, on inspection it was clear that this is just a little push switch. I cut into the cable and added an electrical block connector and gave a quick test to confirm I could power it on and off by simply connecting these two wires. As I wanted to have an Arduino create the connection I decided to use a 2N2222 transistor as I had a couple of these already, you could just as easily use a relay. The connections were as follows:

Pin (flat side to front) Name  Arduino
E – Left Emitter Ground
B – Middle Base Signal (from Arduino)
C – Right Collector Power

I used a 10k resistor between the Arduino and the base of the transistor to add a little protection to the Arduino. You can see from the code that I connected the base pin to pin 8 on the Arduino. Pin 8 need to be set to OUTPUT (pinMode(8, OUTPUT);) and then I to simulate a button press I used the following code:

digitalWrite(8,HIGH);
delay(500);               // wait for half a second
digitalWrite(8,LOW);

To check that the operating system is up I wanted to send ping packets and report on the response, I found a ping library at http://www.blake-foster.com/projects/ICMPPing.zip. Blake created a similar project to this step and I encourage you to check out his site.

Step Two – Energenie RF Power Sockets
This step has been covered in separate blog posts so as not to repeat myself I will provide the links below.
Capture the RF codes for your Energenie Power Strip

PowerShell Power Sockets (Arduino/RF) – Part 1 – Capture the RF codes for your Energenie Power Strip


Configure the circuit like I did in the following post, the code/sketch is similar with the most obvious change being the use of serial as input over web which I’m using in this project.

PowerShell Power Sockets (Arduino/RF) – Part 2 – Configure the Arduino with the RF Transmission Sketch for your Energenie Power Strip

Step Three – IP PDU’s
Again, this step has been covered in a previous post – https://jfrmilner.wordpress.com/2013/01/06/controlling-an-ip-pdu-with-powershell/. As I needed to have the Arduino do the authentication to the IP PDUs I needed to form an HTTP GET request with the username and password encoded. I used the website http://www.motobit.com/util/base64-decoder-encoder.asp which allowed me to encode the default credentials, for example
Username:snmp
Password:1234
Concatenated with a colon join: snmp:1234
Base64 encoded string: c25tcDoxMjM0

To complete the example, below is a code sample of one of the functions I use to collect state information from the PDUs. This clearly shows the use of the authentication code:

client.print("GET /");
client.print(powerState);
client.print("s.cgi?led=");
client.print(LEDCode);
client.println("0000000000000000");
client.print("Host: ");
client.println(hostname);
client.println("Authorization: Basic c25tcDoxMjM0");
client.println("User-Agent: Arduino Sketch/1.0 snmp@1234");

Step Four – The Web Portal/Server
Writing a web server for an Arduino is challenging mainly due to the amount of RAM available. Originally I started this project with an Arduino Uno which is limited to 2K, I maxed this out almost immediately* so I decided to get an Arduino Mega with 8k of RAM. Using the Simple Web Server sketch provided in the Arduino IDE as the starting point I created an HTML table to display the power buttons of the Energenie power strip, this code used up a lot of the available RAM. When I started to add further table rows I soon realised that I would not be able to fit the desired 21 I needed using this format. The solution I used is to have the unique information about these devices within an array and then loop through them to build the page for each client request. This made the code a little more complex but allowed massive reductions in the amount of code I needed to store within RAM.

* see the freeRam code block at – http://playground.arduino.cc/Code/AvailableMemory for an easy way to see memory utilization

Using the original web portal interface for the IP PDUs it required multiple actions to change a power state which I didn’t want and as I have two PDUs I needed to log into each one individually. This should not be considered as a design issue with the devices it’s just that they were not designed for such frequent use or outside a server cabinet for that matter!

IPPDU-05

Instead I wanted it to be mobile friendly so I needed large buttons that were colour coded to their respective devices power state, the below screenshot is taken from my iPad

WebPortal-iPad-1

You will notice that the page fits perfectly; this was achieved by adding this line to the HTML page

<meta name="viewport" content="width=device-width" />

It basically resizes the table to fit to the mobile devices landscape screen resolution and works well on all my iDevices.

In effort to keep the code line count and size down you will notice I created three functions within the Arduino sketch
1.    PDUWebStatus  – Enumerate power states on PDUs
This code queries the current power state of the PDUs and stores the results in an array for use by the aforementioned HTML table loops.
2.    PDUWebCommand – Issue power state changes on the PDUs
This code actions PDU power state change requests.
3.    PDUWebCommandPush – Collect current power state and rotate
This code uses the above two functions to action the HTML button pushes.

Whenever a user presses one of the HTML buttons they call a small javascript function that then calls the PDUWebCommandPush function mentioned above. This makes the users browser send a GET request to the Arduino which then gets matched to one of the predefined actions, for example Energenie Socket 1 On button would trigger the following action

if(buffer.indexOf("GET /?E1=ON")&gt;=0) {
mySwitch.send(4314015, 24);
refreshRequired = 1;
}

You will also notice that this sets the refreshRequired variable, this is used to force the client back to the webservers root directory and allow the changes of power states to be show on the page. I found that redirecting the users back to the root also prevented the refresh button on a browser sending an additional GET request to an already completed request.

Sets
At the time of writing this blog post I only have a single Set as listed on the above image as “Set – 1” but I have plans to add several more. Sets allow me change the power state on multiple devices at once even if they differ power source and/or control method. I have used this to power on my desktop computer and all associated monitors, this is shown in the demo video which accompanies this post.

A note on security
I have controlled access to the Arduino web server using the firewall on my router. This has allowed me to restrict access to my place of work and my internal LAN only.

The Code
The Arduino Sketch can be found over on my GitHub

Well I hope you’ve enjoyed reading about this project as much as I enjoyed putting it together. Please use any of the ideas and code in your own projects but please do give credit to the original author.

Kind Regards

jfrmilner


Today I found myself in a situation where I needed to enter a product key and then activate several Windows 2008 R2 Servers, this would be a real chore if I had to use the GUI.

A quick internet search brought me to slmgr.vbs a great little script that has been included with Windows since Vista/2008 and it even works remotely. Looking at the options on the TechNet page you can see that a simple “slmgr.vbs ServerName -ipk “AAAAA-BBBBB-CCCCC-DDDDD-EEEEE””(Replace the latter with a valid product key) would sort the product key task out for me. To activate and complete the task I would need to use with the following command “slmgr.vbs ServerName –ato”, simple.

One of the tricks I find myself doing again and again from the PowerShell prompt is simple string manipulation, for example:

Get-VM LAB* | % { write "slmgr.vbs $($_.Name) -ipk `" AAAAA-BBBBB-CCCCC-DDDDD-EEEEE `" }

Would create something along the lines of:

slmgr.vbs LAB1-SQL-001 -ipk “AAAAA-BBBBB-CCCCC-DDDDD-EEEEE”
slmgr.vbs LAB1-DC-001 -ipk “AAAAA-BBBBB-CCCCC-DDDDD-EEEEE”
slmgr.vbs LAB1-EX-001 -ipk “AAAAA-BBBBB-CCCCC-DDDDD-EEEEE”

To save yourself even more time you can send the output of the above command directly to the clipboard by piping to “clip”, for example:

Get-VM LAB* | % { write "slmgr.vbs $($_.Name) -ipk `" AAAAA-BBBBB-CCCCC-DDDDD-EEEEE `" } | clip

This allows you to paste back into the console and execute your commands.

After each command executes you are presented with a pop up window like the one below

Activate-01

Now do the same for your activation command

Get-VM LAB* | % { write "slmgr.vbs $($_.Name) -ato" }  | clip

After each command executes you are again presented with another pop up window, this one will look like the one below

Activate-02

Admittedly this is a little quick and dirty and could do with some error checking but it got the job done and saved me a couple of hours work, hopefully it will save others time as well.

Thanks for reading.

jfrmilner


This month I managed to get my hands on an Opengear IP-PDU 9108 8 Port Switched & Metered PDU http://www.opengear.com/product-ip-pdu.html which seems to be a rebranded http://www.digipower.com.tw/PDU/BravoPDUswitched.htm. The PDU can be controlled over the network using a web interface or SNMP.

IPPDU-04

Digipower have an online demo available on the following link http://www.digipower.com.tw/PDU/BravoPDUswitched.htm, at the time of writing this post the address was http://211.75.143.21:8080 (snmp:1234). I’ll demo my code against this test system and if you want to test the code is a safe environment this could be useful for you.

Why bother if you have web and SNMP access?

Well I wanted to do this with native PowerShell cmdlets so that ruled out SNMP and to be quite honest the web portal is great for setting up the main configuration but a bit too long winded to turn a single socket on and off, or get a quick outlet status report. I also wanted to do this with web requests to that I could later use the same techniques learned for this post with an Arduino project I have on my to-do list.

Investigating the cgi and scripts running on the PDU

The PDU’s default configuration is to have the hostname  set to “digiboard” so assuming DHCP is running on your network after a few seconds you’ll be able to connect to the web portal with http://digiboard. I navigated to the Control > Outlet (http://digiboard/outlet.htm) page and selected View Source, near the bottom of the code I noticed a mention of the status.xml:

newAJAXCommand('status.xml'

Let’s starts with the Status.XML, in my browser I loaded up http://digiboard/status.xml and the response was:

<?xml version="1.0"?>

<a href="http://digiboard/status.xml"><response></a><pot0>,,0.4,0.0,0.0,0.0,0.0,0.0,0.0,0.0,1,1,0,0,0,1,1,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,5,5,5,5,5,5,5,0.4,0,</pot0><outn>,,,,,,,,</outn></response>

Jackpot, now I needed to find where in that long response the actual statuses of each of the outlets were. I thought the best to make them stand out was to set them alternate e.g.

1,0,1,0,1,0,1,0 first

Result : ,,0.2,0.0,0.0,0.0,0.0,0.0,0.0,0.0,1,0,1,0,1,0,1,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,5,5,5,5,5,5,5,0.2,0,

and then 0,1,0,1,0,1,0,1.

Result: ,,0.2,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0,1,0,1,0,1,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,5,5,5,5,5,5,5,0.2,0,

This pattern was easy to spot and just to make things as clear as possible for this post I’ve bolded and underlined the areas of interest.

To read this with PowerShell I used the Invoke-WebRequest cmdlet but first I created a variable to hold the credentials to access the web portal (this is just to prevent entering the credentials on each request):

$cred = Get-Credential #Defaults are snmp:1234
$statusXML = Invoke-WebRequest -Uri http://digiboard/status.xml -Credential $cred

Collect the Sub String that we’re interested in:

$statusXML.Content.Substring(52,15)

0,1,0,1,0,1,0,1

That wraps up the Status.xml, now onto turning the outlets on and off.

Also on the http://digiboard/outlet.htm  source code I noticed two functions of interest:

function GetGroupOn()
{
var s = '';
var i = 1;
//for(var i = 1; i < 3; i++)
for(var j = 1; j < 9; j++)
{
if( document.getElementById('C'+ i + j).checked )
s += 1;
else
s += 0;
}
s += "00000000" + "00000000";
if(confirm("turn on the outlet"))
newAJAXCommand('ons.cgi?led='+s, null, false);
}

function GetGroupOff()
{
var s = '';
var i = 1;
//for(var i = 1; i < 3; i++)
for(var j = 1; j < 9; j++)
{
if( document.getElementById('C'+ i + j).checked )
s += 1;
else
s += 0;
}
s += "00000000" + "00000000";
if(confirm("turn off the outlet"))
newAJAXCommand('offs.cgi?led='+s, null, false);
}

You can see from these two functions that either ons.cgi? or off.cgi? is called with two blocks of eight numbers, with a bit of luck I tried:

Invoke-WebRequest http://digiboard/offs.cgi?led=000000010000000000000000 -Credential $cred

Sure enough outlet 8 (H) turned off, let’s try and turn this back on:

Invoke-WebRequest http://digiboard/ons.cgi?led=000000010000000000000000 -Credential $cred

Yep, that worked!

I would guess that the second block of 8 numbers is for 16 outlet PDU’s but I cannot be sure.

Creating the Get-IPPDU function

Using what I discovered I wrote the following function to collect and format the current status of the outlets:

function Get-IPPDU {
<#
.NOTES
Author: John Milner aka jfrmilner
Blog  : https://jfrmilner.wordpress.com
Post  : http://wp.me/pFqJZ-5l
Requires: Powershell V3
Legal: This script is provided "AS IS" with no warranties or guarantees, and confers no rights. You may use, modify, reproduce, and distribute this script file in any way provided that you agree to give the original author credit.
Version: v1.0 - 06 Jan 2013
#>
param(
[System.Management.Automation.PSCredential]$Credential,
$URI = "http://digiboard"
)
try {
$statusXML = Invoke-WebRequest -Uri ($URI + "/status.xml") -Credential $Credential
}
catch {
$_.Exception.Message
break
}
$statusXMLArray = $statusXML.Content.Substring(52,15)
#Status Report
$outlet = 65
$statusReport = @()
foreach ($status in ($statusXMLArray -split ",") ) {
$statusReport += @{$("Outlet" + [char]$outlet)=$status}
$outlet++
}
$statusReport
}

This provides a couple of parameters, URI and Credentials, both are self-explanatory. Here is a screenshot of me trying this against the one on my LAN and the one from the demo site mentioned earlier.

IPPDU-01

Creating the Set-IPPDU function

Using what I discovered I wrote the following function to change the power states of outlets:

function Set-IPPDU {
<#
.NOTES
Author: John Milner aka jfrmilner
Blog  : https://jfrmilner.wordpress.com
Post  : http://wp.me/pFqJZ-5l
Requires: Powershell V3
Legal: This script is provided "AS IS" with no warranties or guarantees, and confers no rights. You may use, modify, reproduce, and distribute this script file in any way provided that you agree to give the original author credit.
Version: v1.0 - 06 Jan 2013
#>
param(
[Parameter(Mandatory=$true)]
[ValidatePattern("[A-H]{1,8}")]
[array]$Outlets,
[ValidateSet("On","Off")] $PowerState,
$URI = "http://digiboard",
[System.Management.Automation.PSCredential]$Credential
)
$outletKeys = [PSCustomObject][Ordered]@{A=0;B=1;C=2;D=3;E=4;F=5;G=6;H=7}
$statusKeys = [PSCustomObject][Ordered]@{ON=1;OFF=0}

$charArray = ("00000000").ToCharArray()
foreach ($request in $outlets ) {
$charArray[($outletKeys.($request))] = "1"
"Turn {0} {1}" -f $request, $powerState
}
$stateString  = -join $charArray
$URI = ($URI + "/" + $powerState.ToLower() + "s.cgi?led=" + $stateString  + "0000000000000000")
Invoke-WebRequest $URI -Credential $Credential | Out-Null
}

We have both the URI and Credentials parameters like the Get-IPPDU function, I also added “Outlets” which accepts the letter name of the Outlet or a comma separated collection of outlet letters and finally the PowerState which accepts On or Off. Here is a screenshot of me testing the functions against the IP PDU on my LAN.

IPPDU-02

I think this is another great example of the power of the new PowerShell 3 Invoke-WebRequest cmdlet and an interesting way to get PowerShell interacting with system/hardware it was never intended for.

These functions should work with any of the digipower PDU’s, such as the Amazing PDU and Bravo PDU. Thanks for reading and as always your comments are welcome.

Regards,

jfrmilner


First Post 1 of 3

Previous Post 2 of 3

So to summarize we have collected all the RF codes for my Energenie Power Strip, created a Sketch on an Arduino connected to a an RF transmitter the only thing left it to use PowerShell to send Serial commands.

Now for the PowerShell code:

function Send-ArduinoSerial {
param ( [parameter(Mandatory=$true, ValueFromPipeline=$true)] [int[]] $byte )
#Find Arduino COM Port
$PortName = (Get-WmiObject Win32_SerialPort | Where-Object { $_.Name -match "Arduino"}).DeviceID
if ( $PortName -eq $null ) { throw "Arduino Not Found"}
#Create SerialPort and Configure
$port = New-Object System.IO.Ports.SerialPort
$port.PortName = $PortName
$port.BaudRate = "9600"
$port.Parity = "None"
$port.DataBits = 8
$port.StopBits = 1
$port.ReadTimeout = 2000 #Milliseconds
$port.open() #open serial connection
Start-Sleep -Milliseconds 100 #wait 0.1 seconds
$port.Write($byte) #write $byte parameter content to the serial connection
try    {
#Check for response
if (($response = $port.ReadLine()) -gt 0)
{ $response }
}
catch [TimeoutException] {
"Time Out"
}
finally    {
$port.Close() #close serial connection
}
}

Once the function has been loaded into your PowerShell console we can turn on and off each of the sockets, for example

Energenie-PSFunctionExample

This is one of those moments when an image fails to express the sheer excitement of a lamp going on and off!

If you forget to plug in your Arduino an exception will be thrown for example

Energenie-PSFunctionExampleError

What’s Next/Further thoughts

  • Program some keyboard shortcuts to power the sockets on and off.
  • Create a web front end and on that note I should point out that Energenie have another solution the LAN Power Management System available, this would be an easier solution for the none techie folks.
  • Try this with a Raspberry Pi

Anyways, thanks for reading my posts and I hope you enjoyed Powering Power Sockets with PowerShell as much as I did!

Regards,

jfrmilner


The WordPress.com stats helper monkeys prepared a 2012 annual report for this blog.

Here’s an excerpt:

4,329 films were submitted to the 2012 Cannes Film Festival. This blog had 25,000 views in 2012. If each view were a film, this blog would power 6 Film Festivals

Click here to see the complete report.


Previous Post 1 of 3

Next Post  3 of 3

Part 2 – Configure the Arduino with the RF Transmission Sketch for your Energenie Power Strip

Continuing on from the previous post where we collect all the RF codes for my Energenie Power Strip we will disassemble the receive circuit and build one for RF transmission.

Connect up your circuit like the below diagram

Energenie-fritzingTx

Here is a photo of mine once completed

Energenie-PhotoTx

My sketch below is a modified version of the “Examples > RCSwitch > SendDemo” Sketch included with the library. Basically the Arduino listens on the Serial port for a byte and if one is found it will check for a matching if statement and actions that code block. Each if statement has been configured for one of the ten possible codes captured earlier and also set to send back a confirmation of which code block was ran, the latter is useful for debugging.

Here is my sketch

/*
 Example for different sending methods
 http://code.google.com/p/rc-switch/
 Edit by jfrmilner for Energenie PowerStrip using Serial input
*/

#include <RCSwitch.h>

RCSwitch mySwitch = RCSwitch();
byte inByte = 0;
void setup() {

 Serial.begin(9600);

 // Transmitter is connected to Arduino Pin #10
 mySwitch.enableTransmit(10);

// Optional set pulse length.
 // mySwitch.setPulseLength(320);

 // Optional set protocol (default is 1, will work for most outlets)
 // mySwitch.setProtocol(2);

 // Optional set number of transmission repetitions.
 // mySwitch.setRepeatTransmit(15);

 //Serial.println("Ready"); // Ready to receive commands
}

void loop() {
 /* Switch using decimal code */
 if(Serial.available() > 0) { // A byte is ready to receive
 inByte = Serial.read();
 if(inByte == '1') { // byte is '1'
 mySwitch.send(4314015, 24);
 Serial.println("1 ON");
 }
 else if(inByte == '2') { // byte is '2'
 mySwitch.send(4314014, 24);
 Serial.println("1 OFF");
 }
 else if(inByte == '3') { // byte is '3'
 mySwitch.send(4314007, 24);
 Serial.println("2 ON");
 }
 else if(inByte == '4') { // byte is '4'
 mySwitch.send(4314006, 24);
 Serial.println("2 OFF");
 }
 else if(inByte == '5') { // byte is '5'
 mySwitch.send(4314011, 24);
 Serial.println("3 ON");
 }
 else if(inByte == '6') { // byte is '6'
 mySwitch.send(4314010, 24);
 Serial.println("3 OFF");
 }
 else if(inByte == '7') { // byte is '7'
 mySwitch.send(4314003, 24);
 Serial.println("4 ON");
 }
 else if(inByte == '8') { // byte is '8'
 mySwitch.send(4314002, 24);
 Serial.println("4 OFF");
 }
 else if(inByte == '9') { // byte is '9'
 mySwitch.send(4314013, 24);
 Serial.println("ALL ON");
 }
 else if(inByte == '0') { // byte is '0'
 mySwitch.send(4314012, 24);
 Serial.println("ALL OFF");
 }
 else { // byte isn't known
 Serial.println("Unknown");
 }
 }
}

Once the Sketch has been uploaded to your Arduino you could use the Serial Monitor to send one of the numbers or any serial aware software for that matter but if you read on to part 3 I will demonstrate doing this with an advanced PowerShell function.

This concludes part 2, I have included links to the next and previous posts below to ease navigation of this blog series

Previous Post 1 of 3

Next Post  3 of 3

Thanks for reading,

jfrmilner


Next Post (Part 2 of 3)

Final Post (Part 3 of 3)

Intro

In this post I’m going to try something a little different, I’m going to explain the process I used to control a four gang power socket with PowerShell. Now I’m only going to be sending serial commands with PowerShell as the hard work is being done by an Arduino and the “rc-switch” library but still this was a really fun project to do and one I wanted to share!

To start, you’ll need all the following items:

Bill of materials:

# Name Price Shop
1 Arduino Uno £15 Google/eBay
2 433 Mhz Transmitter and Receiver £3 eBay: search for “Arduino 433” or “RF Link kit”
3 Energenie Trailing Gang with Four Radio Controlled Surge Protected Sockets £20 https://energenie4u.co.ukwww.amazon.co.uk
4 Breadboard and a few jumper cables Google/eBay

Part 1 – Capture the RF codes for your Energenie Power Strip

To start you will need to connect up your circuit like the diagram below

Energenie-fritzingRx

This is a photo of how mine looked when completed

Energenie-PhotoRx

Like I mentioned in the intro we will be using the “rc-switch” library which can be downloaded from http://code.google.com/p/rc-switch/. Add this to your \arduino-1.0.1-windows\arduino-1.0.1\libraries\ directory and open the Arduino IDE.

Now open the “ReceiveDemo_Simple” sketch and upload this to your Arduino.

Energenie-LoadReciveSketch

Open the serial monitor, assuming everything is wired up correctly when you press the buttons on your remote the codes will appear as “Received <7Digit>  / 24bit Protocol: 1”, for example:

Energenie-COMResults

Collect each of the buttons 7 digit codes into a table so we can use them in the transmission circuit. I recommend using a table, for example:

Switch ON OFF

1

4314015

4314014

2

4314007

4314006

3

4314011

4314010

4

4314003

4314002

ALL

4314013

4314012

This concludes part 1, I have included links to the next and previous posts below to ease navigation of this blog series

Next Post (Part 2 of 3)

Final Post (Part 3 of 3)

Thanks for reading,

jfrmilner


At work this week I was working with one of our Linux engineers and he used the command “cURL ifconfig.me” which promptly provided him with the external IP of the system. I thought to myself, “I wonder if this is possible from PowerShell” and sure enough it is.

Using the Invoke-WebRequest cmdlet we can send http(s) requests to a web service. Note that this is a PowerShell 3.0 only cmdlet.

Let’s give it a try:

Invoke-WebRequest ifconfig.me

Get-ExternalIP-01

Not quite what we’re looking for. On inspection of the website http://ifconfig.me/ we can see that there are many command line options, lets try just the /IP option

Invoke-WebRequest ifconfig.me/ip

Get-ExternalIP-02

Much better and we can clearly see that the IP address is returned in Content which it fine for a quick check at the command line but not so great if your using it for scripting. To collect just the external IP we could wrap the command in parentheses, for example:

(Invoke-WebRequest ifconfig.me/ip).Content

Nice.

I thought that this would make a handy addition to my PowerShell Profile so I created a quick function

function Get-ExternalIP {
(Invoke-WebRequest ifconfig.me/ip).Content
}

Get-ExternalIP-03

Perfect!

An alternative to ifconfig.me is available at http://www.whatismyip.com/ip-faq/automation-rules/, for example

(Invoke-WebRequest http://automation.whatismyip.com/n09230945.asp).Content

Thanks for reading

Regards,

jfrmilner