POWERSHELL DECONSTRUCTED

DECONSTRUCTED

We’re all adventurers.  That’s why we wake up in the morning and do what we do in our fields, for that feeling of mastery and uncovering something new.  Some of us chart new maps, cross the great outdoors, or climb mountains.

And some of us explore code.

In this post, I’ll outline my own such PowerShell adventure, and show you the tools I used to come out the other side with a working solution.  We’ll meet in basecamp to prepare ourselves with the needed gear, plan our scaling strategy and climb the crags of an unknown PowerShell module.  We’ll belay into treacherous canyons, using our torch to reveal the DLLs that make Windows work, then chart new ground using DotPeek and eventually arrive on the summit, victorious and armed with new tools.

 

Continue reading

Advertisements

Lessons on ProcMon and how to force On-screen keyboard

No On Screen Keyboard-

Recently, I had a customer looking at setting up potentially tens of thousands of Point of Sale Kiosks running Windows 10 on an LTSB branch.  We wanted users to have to input their password, but noticed that if a Windows 10 machine is in the docking station, the Touch Keyboard will never display!

Paradoxically, if the user has a Windows Hello Pin specified, that version of the touch keyboard will appear. But for a regular password?  Nope, no On-Screen Keyboard.  And using the dated compatibility keyboard (OSK.exe) was not an option.

To illustrate how weird this confluence of conditions was, I’ve provided a video

While we wait for Microsoft to create a patch to fix this, I’ve created my own workaround, using WMI Events and PowerShell!

In a perfect world, we’d wait for a hotfix. If it affected many people, Microsoft would roll out a patch for it.

Life isn’t perfect and we don’t have time to wait!  Sometimes all you really need is to open up Process Monitor and then write your own hack.

Continue reading

Adding tab-completion to your PowerShell Functions

 

upgrade-your-code

This post is part of the series on AutoCompletion options for PowerShell! Click the banner for more posts in the series!


Probably my single favorite feature of PowerShell isn’t exciting to most people…but I love Auto-Completion.  I have my reasons:

As I have the typing skills of a preying mantis (why did I mention them…they’re easily the creepiest and worst insect…ewww) and constantly typo everything, I LOVE auto-completion.

Add to that the fact that I have lost a memory competition to a gold fish, and I REALLY Depend upon it.

goldfish_1
If you have a memory like me, and like this guy, you’ll love Auto-complete

PowerShell helps deeply flawed people like me by offering tons of built-in help and autocomplete practically everywhere.  Some of it is done for us, automatically, while others require a bit more work from us as toolmakers in order to enable the sweet sweet tab expansion.

In the world of AutoCompletion, there are two real types of AutoComplete that PowerShell offers. In this series, we’ll cover these two types of PowerShell autocompletion:

  • Part 1  – (This post) Parameter AutoComplete
  • Part 2 – (Coming soon) Output AutoComplete

This post is going to be all about the first one.

Parameter AutoComplete

In PowerShell, when you define a Function, any of your parameter names are automatically compiled and available via autocompletion.  For instance, in this very simple function:

Function Do-Stuff {
param(
    $Name,$count)

    For($i = 1 ; $i -le $count; $i++){

        "Displaying $name, time $i of $count"

    }

}

As you’ll see in the GIF below, PowerShell will compile my function and then automatically allow me to tabcomplete through the available parameter names. Continue reading

Registering for WMI Events in PowerShell

registering-for-wmi-events

An alternate title might be ‘Running PowerShell Code ONLY when the power state changes’, because that was the very interesting task I received from my customer this week.

It was honestly too cool of a StackOverflow answer NOT to share, so here it goes, you can vote for it here if you thought it was worth-while.

If you want your code to trigger only when the System Power State changes, as described here, use this code.


Register-WMIEvent -query "Select * From Win32_PowerManagementEvent" `
 -sourceIdentifier "Power" `
 -action {
     #YourCodeHere
      }

Now, this will trigger whenever the power state changes, whether you plug the device in, OR unplug it. So you might further want to stop and pause to ask the question:

Am I on power or not?

Fortunately we can use the WMI Class Win32_BatteryStatus to detect if we’re charging or not, so here’s the full construct that I use to ONLY run an operation when a power event changes, and then only if I’m no longer on Power.

Locking the workstation when the system is unplugged


Register-WMIEvent -query "Select * From Win32_PowerManagementEvent" `
  -sourceIdentifier "Power" `
  -action {
      if ([BOOL](Get-WmiObject -Class BatteryStatus -Namespace root\wmi).PowerOnLine ){
         #Device is plugged in now, do this action
         write-host "Power on!"
     }
    else{
        #Device is NOT plugged in now, do this action
        write-host "Now on battery, locking..."
        [NativeMethods]::LockWorkStation()
     }

If you’re curious how this looks in real time

Registering for device events

It can also be useful to have your code wait for something to happen with devices, such as running an action when a device is added or removed. To do this, use this code.


#Register for power state change
#Where TargetInstance ISA 'Win32_Process'"
Register-WMIEvent -query "Select * From Win32_DeviceChangeEvent where EventType = '2'" `
-sourceIdentifier "Power" `
-action {#Do Something when a device is added
Write-host "Device added at $(Get-date)"
}

You might also want to do an action if a device is removed instead, so use this table to choose which event is right for you. Read more about it here.

EventType Id
ConfigurationChanged 1
Device Arrived 2
Device Removed 3
Device Docked 4

What else can I wait for?

Not only these, but you can trigger your code to execute on a variety of useful WMI Events, all of which can be seen in this image below!

ClassName Triggers when
Win32_DeviceChangeEvent  A device is installed, removed, or deleted, or the system is docked
Win32_VolumeChangeEvent Something happens to your disk drives
Win32_PowerManagementEvent Your device is plugged, unplugged or docked
Win32_ComputerSystemEvent Something major happens to the system
Win32_ComputerShutdownEvent The system is shutting down!
RegistryEvent Anythign happens to the registry
RegistryKeyChangeEvent A reg key you specify is changed
RegistryValueChangeEvent A reg value you specify is changed

Part VI – In-Depth Building the FoxDeploy DSC Designer

series_PowerShellGUI

This post is part of the Learning GUI Toolmaking Series, here on FoxDeploy. Click the banner to return to the series jump page!


Where we left off

Thanks for joining us again!  Previously in this series, we learned all about writing fully-fledged applications, in Posts 1, 2 and 3. Then, we learned some techniques to keeping our apps responsive in Post 4.

In this post, I’ll walk you through my GUI design process, and share how that actually worked as I sought to create my newest tool.

Along the way, I’ll call out a few really confusing bugs that I worked through in creating this tool, and explain what went wrong. In particular, I ran into quite a snag when trying to programmatically create event handlers in code when trying to use $psitem  or $_. This lead to many conversations which introduced me to a powerful solution: the $this variable.

What is the tool?

Introducing the FoxDeploy DSC Designer.

imaage base layer designed Designed by Freepik
Think something sort of like the Group Policy Management Console, for your DSC Configurations. But we’ll get back to this in a few minutes.

My GUI Design Process

Here’s my general process for designing a front-end:

  • Create the elevator pitch (Why does this need to exist?)
  • Draw out a rough design
  • Make it work in code
  • Add feature by feature to the front end
  • Release
  • Iterate

It all started with me taking a trip to Microsoft last year for the MVP Summit.  I’d been kicking around my elevator pitch idea for a while now, and was waiting to spring it on an unwary Microsoft Employee, hoping to con them into making it for me:

Here’s my elevator pitch

To drive adoption of DSC, we need some tooling. First, we need a GUI which lists all the DSC resources on a machine and provides a Group Policy Management Console like experience for making DSC configs.

We want to make DSC easier to work with, so its not all native text.

I decided to spring this on Hemanth Manawar of the PowerShell team, since I had him captive in a room.  He listened, looked at my sketches, and then said basically this:

‘You’re right, someone should make this…why not you?’

Thanks guys.  thanks

So I got started doing it on my own.  With step one of the design process –elevator pitch– out of the way, I moved on to the next phase.

Time to draw a Rough Draft of the UX

Continue reading