I’ve written this up on the new website for our Rochester PowerShell group and on the old blog, and on UGSS Facebook and Twitter … and now that there’s only two days left, it’s time to mention it again, on my blog
It’s a new year, and a new opportunity to get started with PowerShell. With the new year, we’re going to put a renewed focus on trying to make our meetings valuable to everyone. With that in mind, the first Rochester meeting of the upstate New York PowerShell users group in 2010 will feature two separate presentations:
Everyone is welcome, from beginners to pros! Bring a friend and introduce them to PowerShell. As always, our meeting will be at New Horizons’ in Henrietta, 50 Methodist Hill Drive, Suite 50.
In order to keep things on time, we’ll be starting our presentations at 6:30 exactly, after a short pizza, wings, and networking time starting at 6pm. We only ask that if you can come early for the food you let us know ahead of time and come ready to pitch in a few dollars to help cover the cost.
PS: There will be swag. We have several books, an Arc Mouse, and copies of Windows 7 and Office 2007 to give away…
I was under the impression that module manifests allow only DATA stuff. In fact, if you try to use cmdlets or variables in them, you get the usual Data-language errors, like this:
Import-Module : The module manifest ‘C:\Modules\Test\Test.psd1’ could not be processed because it is not a valid PowerShell restricted language file. Please remove the elements that are not permitted by the restricted language: The command ‘Get-ChildItem’ is not in allowed in restricted language mode or a Data section.
Import-Module : The module manifest ‘C:\Modules\Test\Test.psd1’ could not be processed because it is not a valid PowerShell restricted language file. Please remove the elements that are not permitted by the restricted language: A variable that cannot be referenced in restricted language mode or a Data section is being referenced. Variables that can be referenced include the following: $PSCulture, $PSUICulture, $true, $false, and $null.
BUT THEN I came across this in the Windows 7 built-in BitsTransfer module:
RequiredAssemblies=Join-Path $psScriptRoot “Microsoft.BackgroundIntelligentTransfer.Management.Interop.dll”
AND IT WORKS?!
Well, that’s very weird, because Join-Path is certainly not allowed in a normal “restricted language” file, and (as you can tell from above) neither is $PsScriptRoot — in fact, as far as I know, you shouldn’t have to do that at all, since RequiredAssemblies knows enough to look in your module folder… but nevermind that, why does it work?
So I went digging, and it turns out that although they are parsed as Restricted Language (like a “data section,” see about_Data_Sections), module manifests are allowed extra cmdlets: “Import-LocalizedData”, “ConvertFrom-StringData”, “Write-Host”, “Out-Host”, “Join-Path” and even special variables that aren’t normally allowed in data sections: specifically $PsScriptRoot which is the ModuleBase (the parent folder of the psd1) and environment variables ($Env:), plus the usual $PSCulture, $PSUICulture, and of course $true, $false, and $null.
However, although you can use those variables, you can’t embed them in strings, so if you wanted to use $Env:Windir or $Env:Temp as part of a path (for instance), you need to take advantage of the availability of Join-Path.
Now, I can’t find this documented anywhere (although I did add it to the module manifest documentation on MSDN), but it’s true, nonetheless — you’ll just have to trust me
Yeah, PowerShell is starting to drive me crazy again.
Shay Levy, ScriptFanatic, wrote about the PowerShellHostVersion on his blog this morning, explaining how it is not a field you should use in your module manifests.
Of course, there’s an exception: if your module is dependent on a specific host. For instance, if you’ve written a module for PoshConsole which exploits the WpfHost display features or the BgHost hotkeys feature … or if you’ve written ISEPack based on the menu and script-editor features of PowerShell ISE), then it makes sense to specify the PowerShellHostName and the PowerShellHostVersion together. However, if you aren’t taking a dependency on a specific host … you should definitely never specify PowerShellHostVersion by itself.
I’ve got another one that I think you should not use. PowerShell has several ways of specifying prerequisites for your modules, such as assemblies that should be loaded, modules that must be nested, etc. In every case except RequiredModules, PowerShell will actually import those things for you.
That is, if you specify that you RequiredAssemblies = “System.Windows.Forms” it will automatically load it. If you specify NestedModules = “BitsTransfer” it will automatically load that. But if you specify RequiredModules = “BitsTransfer” you’re sore out of luck.
Not only does PowerShell not load them for you, it doesn’t give you all the information you need to load them when it fails. For example, consider that you have a module called “ReallyRequired” and one called “TestModule” which requires ReallyRequired. It’s metadata file is very simple, it looks like this:
Before we try to import it, we might try to check which modules it requires, and since it doesn’t appear to require any, we’ll go ahead and import it:
Apparently, there’s just no way to tell which module(s) you need to preload (or even whether there are any) until you get an error message. You might think you could just write a script to test for that error and then run Import-Module ReallyRequired … but what you don’t know is that after you load your copy of the ReallyRequired module:
If you’re like me, right now you’re tearing out your hair wondering why the error message didn’t tell you that in the first place. Then you have to go off and try to find a newer version of your RequiredModules. And that’s not even the crazy thing! The crazy thing is, if you find the wrong one, you could still get a message about the GUID not matching next.
So yeah, RequiredModules is really unlikely to be helpful right now. You’re better off just putting an Import-Module ReallyRequired -version 2.5 -ErrorAction Stop at the top of you script module (although that won’t help you if you’re writing a binary cmdlet module).
This is just one of the things that the new PoshCode is being designed to address, so I’ll be blogging more about this shortly, but for now, you can use this function to list RequiredModules:

This is old news and new news … but I figured it’s about time I break it on my blog, since it was mostly my doing (and since my Northeast Developer Evangelist Jim O’Neil already mentioned it on his blog).
We have created an official Virtual PowerShell Group (official, in the sense that it’s recognized by Microsoft’s User Group Support Services out of the unofficial #PowerShell channel on irc.freenode.net and have created a website to support it including a page where you can join us online via web-based chat any time you like.
Of course, this isn’t exactly headline news: The #PowerShell IRC channel has been around for years and has always been helpful and polite. What’s new is that we are officially a User Group, and have swag to give away (more on that later)! We’re hoping that this will help some of you justify joining us, and using IRC as a resource for your PowerShell learning and for those sticky questions!
I just posted an article to the FAQ on the PoshCode Wiki answering this question that came up again on our IRC PowerShell user group today. It came up in the context of determining whether a function was the last function on the pipeline, because one of our users was looking for a way (other than creating ps1xml files) to output objects onto the pipeline for use in other functions, but still format those objects nicely if they were output directly.
Before I give the solution, I just want to say: don’t change your output based on where you are in a pipeline.
There are numerous scenarios where your function will be the last one on a pipeline, but still be participating in further pipelines, including formatting and output modification. For example, take our function Test-Pipeline (defined below) in these three scenarios below. In none of these scenarios would it be appropriate for the function to write formatted output instead of outputting the raw object, but in each case, the function is the last function in the pipeline.
However, if you want to determine your function’s position in the pipeline for some other reason, the answer is simple. You need to use $MyInvocation and compare the PipelineLength and PipelinePosition properties:
So, the Windows PowerShell 2.0 Software Development Kit is basically a collection of samples, and it has been released separately from the Windows Platform SDK for a change, making the download a tiny 2.35MB …
There are lots of examples in there in C# (no other languages), and honestly, some of them ought to make it into PSCX or some other project where people could grab pre-compiled versions
Honestly, if you’re a developer that’s been wondering about learning to code cmdlets, or host PowerShell as a scripting engine, now’s the time.
I know that I just wrote a post last week about XPath and namespaces in PowerShell, but at the time I left out one possible way of dealing with namespaces, because it’s not the right way of doing things. However, sometimes it’s nice to have options, and when you’re working on the command-line in PowerShell, or just trying to figure out a proof-of-concept call to a web service, you really don’t need to deal with namespaces correctly, you just need it to work.
With that in mind, I present to you the fourth option: just strip the namespaces out! The simplest way to do that is to run the XML through an XSL stylesheet which just outputs the local-name() of each node (including attributes), and remove any namespace definitions (processing instructions).
That stylesheet and the basic steps of the process will work anywhere, from Java to C# to the web … but since my current language of choice for prototyping is PowerShell, I’ll show you how to implement it there as Remove-XmlNamespace. Once you have that, I think you’ll see that it was relatively simple for me to write a new Select-XML which adds a parameter RemoveNamespace which is implemented by calling this Remove-XmlNamespace …
That actually allows you to call Select-Xml with the -RemoveNamespace parameter just as though the namespaces didn’t exist. Of course, the returned XML nodes will, in fact, NOT have namespaces … so they may not be quite the same as the source, but the data will all be there.
A while back Thell Fowler (with a little help, and a lot of testing from me) wrote a very good PowerShell Lexer for Notepad++ 5.2 and later… it’s very thorough, has good code-folding, and full support for PowerShell 2.0 syntax highlighting.
I mention this because Notepad++ 5.6 just released yesterday, and it has built-in support for PowerShell syntax courtesy of Scintilla ... but it’s very, very bad. The scintilla PowerShell lexer is probably the most minimal PowerShell lexer I’ve seen (it’s worse than the old “user style” I had created for Notepad++) and has no support for:
There’s probably more, but I couldn’t be bothered to spend more than a couple of minutes with it. As you can probably guess … all of those features are supported by the external PowerShell Lexer plugin that Thell wrote, so if you’re a PowerShell and Notepad++ user, I apologize for not drawing your attention to our PowerShell Lexer for Notepad++ before
.
Incidentally, I stuck a screenshot in this post so you can see how I use it, but there’s one a more complete example of the PowerShell Syntax Highlighting on that lexer download page.
Although there are a few “CSS Selector” libraries, most browsers haven’t even implemented CSS3 selectors, never mind frameworks like .Net or scripting languages like Javascript or PowerShell
so XPath remains the most powerful way to deal with finding specific data in an XML file, and by extension, XHTML and even HTML files (if you can convert them using something like SgmlReader) is to use XPath queries.
There are a lot of XPath tutorials around the web, so there’s no need for me to get into that very much, but I just wanted to write a brief note about using XPath with documents that have namespaces (particularly, from .Net). The problem is that in order to select nodes that have a namespace assigned, you must use a namespace prefix and a NamespaceManager. So even if it’s the default namespace, if there’s an xmlns=”...” on the document, you have to create and use a prefix.
The bottom line is this: if you have an XML document that looks like this:
That bit at the top where it says: xmlns="http://schemas.microsoft.com/win/2004/08/events/event" is assigning a default namespace. Sometimes you’ll see something like this (eg: in RSS):
This one assigns a specific prefix “media” to the namespace url “http://search.yahoo.com/mrss/” ...
In either case, if you want to select a node that’s assigned to a namespace (which is ALL the nodes in the first example, but just the ones that start with media: in the second example) in .net, you have to specify the namespace in order to select those nodes with XPath. PowerShell 2.0 has a Select-Xml cmdlet which accepts -Namespaces as a parameter: you simply provide a hashtable of names to urls.
If you had loaded the first document above into $xml, you could select the BootStartTime and BootEndTime using an XPath query like this: //e:Data[Name = ‘BootStartTime’ or Name = 'BootEndTime'] but we have to DEFINE that “e” namespace. To do so using Select-Xml you just pass it into the command
Of course, you don’t have to use Select-Xml, you can do this in plain .Net without cmdlets (and this is what you would have to do in C#). In fact, depending on the situation, it might even be simpler:
There are, however, two ways that you could avoid specifying the namespaces. The first is to just avoid specifying the node name at all. In that first example, that would be fairly easy, because the “BootStartTime” and “BootEndTime” names are unique to the nodes we’re interested in (even if there were boatloads of identical events, you’ll never have a Name=“BootStartTime” attribute on the
So to ignore the tag name, we can just use a * for a wildcard. The only real difference is that we don’t need the namespace, and the XPath pattern will be different:
Or to specify the local name, we can use the Local-Name function. Again, we don’t need a namespace, we are just changing the XPath to be a more specific match:
I write a lot of PowerShell scripts, and I work on modules a lot, including ones which I load automatically in my profile. Sometimes I forget to sign those modules before I restart my console/host, and then I get errors when they’re loaded from the profile. I wrote a script to solve this problem by automatically signing files every time they’re edited, and I figured I’d share it below, but first let me try explaining what code signing is, and why you should care.
Code signing is the process of digitally signing files to confirm the author and guarantee that the file has not been altered or corrupted. It’s essentially the same as signing emails: it guarantees that they were actually authored by the person claiming to be the author, and that they weren’t changed after the author signed them. (For more information see Apple’s explanation and Microsoft’s).
Basically, digital signing is cryptography, so a full understanding of it really requires taking a 400-level college course, but here are the basics: You take some data (binary bits) and use a well-known algorithm to calculate what is called a “hash” of the bits. This hash is mathematically-generated from the source data, and so it can be re-calculated by the receiver. The hash is then “signed” via another algorithm: using a private key (see Public Key Infrastructure (PKI) for more about how these keys are managed) the signer encrypts the hash and attaches it to the file.
With public/private key encryption, data that is encrypted by the private key can be decrypted by the public key, so the encryption of the hash (and sometimes the public key, as well) is attached to the file so that the end user can re-calculate the hash and decrypt the signature to verify: a) that it was encrypted by the private key belonging to the author, and b) that the hash matches the hash that the author signed.
In PKI, the “key” is actually part of what’s called an SSL certificate issued to you by a Certificate Authority (CA) who verifies your identity. Verisign introduced the idea of “classes” for certificates, and you can now get free, Class 1 certificates for email signing from most CA’s now (like Thawte and Comodo and StartCOM), where the only thing they verify is that the person being issued the certificate can send/receive email at that address.
Of course, if you want to verify yourself as the author of code, we want to know more about you than your email address. So to sign code, you need at least a Class 2 certificate, for which proof of identity is required. This typically comes in the form of providing (photos of) your passport, driver’s license and/or other photo ID to verify that you are who you claim to be, and answering a few questions on the phone to validate that you own the phone number provided… or providing tax or other documents to prove the existence of an organization and that you’re qualified to speak for them. There are also additional classes: Class 3, 4, and 5 are extended validation certificates used for servers, software signing, b2b transactions and government security.
Well, the chances are, you don’t need to. Script signing is really a feature for corporations. The idea is that scripts from your IT department need to be verifiable and unalterable… code-signing gives companies a way to lock down and secure PowerShell scripts: setting a global policy requiring script signing, and ensuring that all scripts produced by the corporate administrators are properly signed…
As an individual, script-signing doesn’t really offer you much unless you share your computer with other administrator users. After all, what it protects you from is intentional or accidental altering of the script. If there’s no one else who has access to your computer, then nobody can alter your scripts. Of course, if someone hacks your computer enough to alter or create files on your hard drive and wanted to do something malicious, scripts would be a silly thing to target
There is, however, one additional time when you might want to sign your scripts. If you’re distributing scripts, whether via PoshCode.org, the TechNet script gallery, or on CodePlex or the MSDN code gallery … signing them gives you (and your users) the assurance that you are the author, and they haven’t been altered. In fact, the PoshCode Module which is available on PoshCode.org, and which allows you to search and download (as well as upload) PoshCode scripts uses script signing to allow it to safely upgrade itself. It features a Get-PoshCode -Upgrade command which will check for, and fetch, the latest version of the PoshCode module, and then validate it’s code signature is the same as the previous one before using it.
Remember, code signing cannot:
Assuming that after skimming all of that, you want to try signing your scripts, you need a certificate. You can generate one yourself (although it’s not easy, and the signed scripts which will only work locally on your system, and won’t be trusted by anyone else) or you can get one from a public Certificate Authority (I recommend StartCom/StartSSL which only costs $40 for two year certificates).
Typically, your certificate will be a .pfx file which you can load using Get-PfxCertificate, or you might have imported it into your local certificate store using CertMgr.msc, in which case you can load it using Get-Item Cert:\CurrentUser\My\ with the thumbprint of the certificate. In either case, you’ll have a certificate object you can pass to Set-AuthenticodeSignature along with the file path.
Awhile back I wrote an Authenticode Script Module which has wrappers for signing and testing signatures on scripts. It uses a metadata file (which you have to create yourself) with a PrivateData variable that points to either the thumbprint of a certificate you’ve imported to your computer’s certificate store, or the path to a .pfx file … and allows you to sign files by just writing sign .\FileToSign.ps1 without having to Get-PfxCertificate each time, or even remember to turn on the -TimeStampUrl feature so that your signed scripts stay signed even after the certificate expires. That script helps a lot, but I’ve been wanting my text editor to sign the scripts automatically when I save them …
I mostly use Notepad++ for editing PowerShell scripts (with a PowerShell Syntax lexer I helped create), but after playing with the idea of writing a plugin to sign things after saving, I ended up deciding to go with something simpler: a PowerShell script to watch a folder for changes and sign any scripts I edit or save.
I’ve added a function I call Start-AutoSign to my authenticode script module which takes a path and a -Recurse flag and sets up a System.IO.FileSystemWatcher to detect saves, creates, and moves … and (re)sign the script if it needs it. Here is Start-AutoSign without the help docs or anything (so I can discuss it). You should just download the whole script module if you want to use it
A few things to notice: first, I’m assuming you’re using my Set-AuthenticodeSignature wrapper, so by default I don’t pass it an actual certificate. Second, in order to avoid eternally looping and re-signing the script over-and-over, you have to have a way to make sure you don’t re-sign it when it “changes” because you signed it. The approach I took was to test and see if the signature was valid or not (and if it’s valid, then don’t sign it again). Third: when you Get-AuthenticodeSignature, the Status codes leave much to be desired, returning the same “UnknownError” in several cases where they know exactly what the error is. You can check the StatusMessage and see that they even tell you what the error was:
There may be other reasons too that I haven’t encountered yet, but the one thing we’re concerned with is the first one that the “form” isn’t supported. That means this is a file type which Set-AuthenticodeSignature can’t sign. PowerShell’s signing only works with executables, PowerShell scripts, modules, metadata, and xml files … so there’s no point trying to sign anything else. You may also notice that in my script (by default) I’m only signing .ps* files (that is: scripts, modules, metadata and ps1xml files), and that’s because with .dll and .exe files, I would prefer to sign them as part of my build step anyway.
One last thing: as with a few of my recent scripts, this one is designed to use Growl for Windows to notify you whenever it signs anything. If you don’t have the Growl module available, it should just skip right over that without any problems, but you can disable it in any case with the -NoNotify switch. Personally, I like seeing the popup so that I know it’s working, and know that I’m not accidentally signing something … and I love Growl for script notices because I can skin it, configure sounds, and forward the notices to other machines … or even temporarily disable them, all without having to tweak scripts.