At first glance, PowerShell appears to be yet another command shell with the interesting twist that you pipe objects between commands rather than strings. But there is more to PowerShell than that. One fascinating area is PowerShell Providers. (PowerShell Providers aren’t anything new as they’ve been there since v1. So I’m not the first – nor will I be the last – to blog about them, but hopefully some folks starting out with PowerShell find this useful…)
We’ll start with a simple example using “ls” to list the contents of a directory:
ls c:\
Now “ls” is just a two-letter version of “dir” and both are aliases for “Get-ChildItem”. How do I know that?
ls alias:
This prints out all current aliases. That funky “alias:” is a PowerShell provider. If you want a specific alias, you can “ls alias:ls” or “ls alias:dir”.
To get a list of currently installed PowerShell providers, you can use Get-PSProvider:
You should notice a few interesting entries there. You want a list of environment variables? The Environment provider does the trick:
Note that providers aren’t read-only. Let’s say you want to temporarily add a directory to your path. In cmd.exe, you would do the following:
set PATH = %PATH%;<EXTRA_DIR>;
In PowerShell, you use the Environment provider:
$env:PATH += “;<EXTRA_DIR>”;”
Notice the env: prefix that tells PowerShell that the variable is handled by the Environment provider. (Notice above that “Env” is listed as the “drive” for the Environment provider.)
Let’s explore some more…
Notice that changing drive letters is actually handled by the Function provider and are just commands.
It gets more interesting with the Registry provider through which you can access HKEY_LOCAL_MACHINE via hklm: and HKEY_CURRENT_USER via hkcu:.
You even get tab completion while typing. (Try ls hkcu:<TAB><TAB><TAB> to see various subkeys for HKEY_CURRENT_USER.) And assuming that you have write permission to the registry keys, you can set them too!
PowerShell providers aren’t limited to those shipped by Microsoft. You can in fact write your own, though I’ve never tried it. People have written their own providers for everything from SharePoint to Subversion.
So go check out PowerShell providers. Happy Scripting!