Monthly Archives: January 2010

MS-DOS and cmd.exe shell power users remember for sure how easy it was to write a script (or any other text file) quickly from the command line without an editor. It was possible to copy the CON device (which stands for Console meaning keyboard/input and monitor/output as one device) to a file, for example COPY CON TEST.CMD. Once a COPY CON command has been invoked, it was possible to type whatever you want, even multiple lines were possible. When completed you could save the file and return to the prompt by pressing CTRL-Z (or F6) which would create ^Z (end of file) and then press Return.

In PowerShell there’s a similar approach as well but it doesn’t correspond one-to-one. The trick takes advantage of a single-quoted here-string to create a script:

PowerShell

1

2

3

4

5

6

7

8

9

10

11

12

13

PSC:\Users\Pit>@'

>> "Hello, ${Env:USERNAME}!"

>> "There are $((Get-ChildItem).Count) files and folders in this directory: $pwd"

>> '@>.\test.ps1

>>

PSC:\Users\Pit>cat.\test.ps1

"Hello, ${Env:USERNAME}!"

"There are $((Get-ChildItem).Count) files and folders in this directory: $pwd"

PSC:\Users\Pit>

PSC:\Users\Pit>.\test.ps1

Hello,Pit!

There are15files and folders inthis directory:C:\Users\Pit

PSC:\Users\Pit>

Actually, Here-strings are used to embed more or less large text blocks inline in scripts. Here-strings start with “@” plus double- or single-quote followed by newline and end with newline, double- or single-quote followed by “@”.

My first blog post of the new year deals with the signing of PowerShell scripts. I want to share a function called Sign-Script that eases the process of adding a signature to one or more PowerShell scripts:

Basically, the Sign-Script function invokes the Set-AuthenticodeSignature cmdlet accordingly for each script file that was either passed as value of the FilePath parameter or as pipeline input.

By default, the function uses the Get-ChildItem cmdlet to get a code-signing certificate in the cert:\CurrentUser\My subdirectory of the certificate store. Alternatively, the function will use the Get-PfxCertificate cmdlet to find the .pfx certificate that was passed as value of the PfxCertificate parameter.

The Sign-Script function should be considered very basic. You can test it without any risks as I have used the WhatIf parameters that invokes the Set-AuthenticodeSignature cmdlet. Hope you like it anyways.