Skip to content

posh tips to remember : date, timespan, switch, array to array assignments, split with regex


Found a script in my mails. It contains nice things that are good to remember:

$lunchtime = get-date -hour 12 -minute 30

This sets the variable to a special point in time on the current date

$timespan = New-TimeSpan -End $lunchtime

Timespan is caculated as the difference from the current time until ore since the $lunchtime.

switch ($timespan) {

($_ -lt 0 )  { “lunch is over”}

Switch can not only compare to fixed values but you can also use expressions. The variable in the switch-statement (here $timespan) is put to the $_ variable .

From another thing I got some more tips that I should remember

netstat -an |
ForEach-Object {
$i = $_ | Select-Object -Property Protocol , Source , Destination , Mode

this creates for each line in the output from the netstat command a new object in the variable i

you must use the $_ |   evene when you have no matching attributes , otherwise the select-object will not create an attribute with the empty properties.

$null, $i.Protocol, $i.Source, $i.Destination, $i.Mode = ($_ -split ‘\s{2,}’)

here I find two things remarkable:

first you can use a list of variables and assign each variable the n-th element of a list on the right site

2nd the -split operator recognizes regular expressions like the \s{2,}

Leave a Comment

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: