Monthly Archives: January 2010

  • 1

Copy Con For PowerShell?

Hello again! This time I share a quick tip.

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:

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 “@”.


  • 3

Easy PowerShell Script Signing

Hello again. Wish you all the best for 2010.

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:

function Sign-Script ([String[]]$FilePath, [String[]]$PfxCertificate)
{
begin
{
function sign ($filename, $cert)
{
Set-AuthenticodeSignature -FilePath $filename -Certificate $cert -WhatIf
}
if ($PfxCertificate)
{
$cert = Get-PfxCertificate -FilePath $PfxCertificate
}
else
{
$cert = @(Get-ChildItem -Path cert:\CurrentUser\My -CodeSigningCert)[0]
}
}
process
{
if ($_)
{
if ($_ -is [IO.FileInfo])
{
sign -filename $_.FullName -cert $cert
}
else
{
sign -filename $_ -cert $cert
}
}
}
end
{
if ($FilePath)
{
foreach ($file in $FilePath)
{
sign -filename $file -cert $cert
}
}
}
}

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.