Showing posts with label powershell. Show all posts
Showing posts with label powershell. Show all posts

Tuesday, October 18, 2011

Switch/Flag Parameters in PowerShell

I wanted to create a function with a ‘-force’ option.  First, I tried to add a [boolean] parameter, but that doesn’t work because it needs a value with the argument; I want it to be invoked with just the presence of the switch/flag.  Here’s how I finally did it:

function Update-Something {
param(
[switch] $force)

if ($force) {
#do something here
}
}


# use like:
$> Update-Something -force

Thursday, October 13, 2011

Rounding In PowerShell

Another simple one (from John D. Cook):

$> [int] 1.1
1

$> [int] 1.5
2

$> [int] 1.8
2

PowerShell: Parse Date from String

Incredibly simple (checkout this PowerShell Cookbook):
$> (get-date 2000/01/01)

Saturday, January 01, 2000 12:00:00 AM

Tuesday, October 4, 2011

PowerShell Format-List (fl)

Staying with the late to the party theme on my PowerShell adventure, today I discovered Format-List (fl alias).  You can pipe results into it and get more detailed output.

Without Format-List:
PS> [Array]

IsPublic IsSerial Name BaseType
-------- -------- ---- --------
True True Array System.Object
With Format-List:
PS> [Array] | fl

Module : CommonLanguageRuntimeLibrary
Assembly : mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b7
7a5c561934e089
TypeHandle : System.RuntimeTypeHandle
DeclaringMethod :
BaseType : System.Object
UnderlyingSystemType : System.Array
FullName : System.Array
AssemblyQualifiedName : System.Array, mscorlib, Version=4.0.0.0, Culture=neutral, Pub
licKeyToken=b77a5c561934e089
Namespace : System
GUID : 200fb91c-815d-39e0-9e07-0e1bdb2ed47b
IsEnum : False
GenericParameterAttributes :
IsSecurityCritical : False
IsSecuritySafeCritical : False
IsSecurityTransparent : True

Monday, October 3, 2011

PowerShell RegEx

Trying to learn PowerShell by using it to create a NuGet build scripts. In order to parse some code files, I needed to filter a list of strings using a regular expression and capture a match group from the first string matched:
$line = 
    $assembly_info | 
    where {$_ -match 'AssemblyDescription\("(?<1>[^"]*)"\)'} | 
    select -first 1

$matches[1]
Looks almost like a functional language.  Better late to the party than never…