Signing powershell scripts

Extracted from an blog post by Scott Hanselman

Create a Local Certificate Authority certificate

  makecert -n "CN=PowerShell Local Certificate Root" -a sha1 -eku 1.3.6.1.5.5.7.3.3 -r -sv root.pvk root.cer -ss Root -sr localMachine

Make a personal certificate from the previously created root certificate

  makecert -pe -n "CN=PowerShell User" -ss MY -a sha1 -eku 1.3.6.1.5.5.7.3.3 -iv root.pvk -ic root.cer

Verify the certificates in PowerShell

Get-ChildItem cert:\CurrentUser\My -codesign

Sign a script

Set-AuthenticodeSignature c:\foo.ps1 @(Get-ChildItem cert:\CurrentUser\My -codesign)[0]

Hash tables

Content shamelessly stolen from SS64

Initialise the Hash Table

$array_name = @{key1 = item1; key2 = item2;...} 
# Keep fields ordered with [Ordered]
$array_name = [Ordered]@{key1 = item1; key2 = item2;...}

Add items to a Hash Table

$usa_states.Add("GA", "Goregia")

Edit items in a Hash Table

$usa_states.Set_Item("GA", "Georgia")

Combine Hash Tables

$world_states = $usa_states + $india_states

Remove items from a Hash Table

$usa_states.Remove("GA")

Retrieve items from a Hash Table by key

$usa_states.'NY'

Pipeline-friendly function

function Some-Function {
  Param (
      [parameter(
          ValueFromPipelineByPropertyName = $true, 
          ValueFromPipeline = $true)]
      [int[]]$SomeValue)
      
  Process {
    $SomeValue | % {
      # Do the stuff here on each value item 
      "$_ + 2 = $($_ + 2)"
    }
  }
}

Powershell pipeline-friendly function test

Miscellaneous

Search for a range of files

gci has a filter (-fi) parameter, but only accepts a single string. Sometimes you want to provide a number of filters. You can use include (-i) to achieve this, but MUST then provide a base path.

get-childitem .\* -r -i *.h, *.hpp, *.c, *.cpp | % { $_ }

Return the value of a regular expression match

get-content SomeTarget.txt | ([regex]"<pattern_text>").Matches($_) | 
    % { $_.Value }

Create a custom object from a pipeline

get-childitem SomeFolder | 
    % { new-object psobject -property @{ Col1 = 1; Col2 = 2 } }
# Create an ordered hash table
get-childitem SomeFolder | 
    % { new-object psobject -property ([Ordered]@{ Col1 = 1; Col2 = 2 }) }

Suppress type info from CSV files

$SomeData | export-csv target.csv -NoTypeInformation

Stop on the first error

$ErrorActionPreference = "Stop";