My First PowerShell Cmdlet

We’ve been using PowerShell to write automated tests of the UI on my current project.  One of the tasks I took on today was creating a custom cmdlet to enable us to select radio buttons.

I already had an existing assembly of cmdlets to work with, so I just added a new class (SelectRadioButton) to it.  Next, I added references to System.Management.Automation and System.Windows.Automation. With these references in place, I could add this attribute to the class:

[Cmdlet(VerbsCommon.Select, "RadioButton", SupportsShouldProcess = true)]

The attribute determines the actual name of the cmdlet you’ll use in scripts (Select-Radiobutton).  The cmdlet needs an instance of AutomationElement to operate on, so that’s defined next:

[Parameter(Position = 0, Mandatory = true, HelpMessage = "Element containing a radio button control")]
[ValidateNotNull]
public AutomationElement Element { get; set;}

Finally, I adapted some of the logic for my override of the ProcessRecord from this article on using UI automation.  The end result looks something like this:

protected override void ProcessRecord()
{
try
{
if (Element.Current.ControlType.Equals(ControlType.RadioButton))
{
SelectionItemPattern pattern = Element.GetCurrentPattern(SelectionItemPattern.Patern) as SelectionItemPattern;
if (pattern != null) pattern.Select();
}
else
{
//Put something in here for handling something other than a RadioButton
}
}
catch (Exception ex)
{
// You could put some logging here
throw;
}

}