PowerShell tips and tricks, part #1

This is translation of my article about some PowerShell tips & tricks not only for developers. I will split the article into more parts, so you won't get tired too early ;)

From time to time when working with Powershell you will find something interesting or a general pattern that makes your work easy or that helps you to understand some basics of PowerShell. In this article I will show you some of my tips and interesting useful patterns. Note that this article highlights only some of them. I had to select only some.

I won't touch advanced topics, that you will use only sometimes. I aim at everyday usage of PowerShell. Anyway, I hope at least some of them will be new to you.

Arbitrary names of functions

There are two scenarios how PowerShell is used. You have either your code snippets stored in script files and run them when needed (scheduled scripts, tools, modules, etc.). Or you just type in console and run the code immediatelly after you hit Enter.

When working with scripts, it is very important to keep them readable, comprehensible and independent. That's why you should use full cmdlet names and not only aliases (gci vs. Get-ChildItem). Alias gci can mean something completely different on other machine.

When working with console, your requirements change. You use aliases very frequently and type the shortest code, (gci|?{!$_.PSIsContainer}|select -exp Length). The important thing is to reach the goal, no matter how.

PowerShell makes things easy, because you can use pretty interesting names for your functions and aliases. Let's have a look at some examples:

[0]# well known functions ?? a ?:
[1]function ?? { if ($args[0]) { $args[0] } else { $args[1] } }
[2]function ?: { if (&$args[0]) { $args[1] } else { $args[2] } }

[3]?? $null 'default value'
default value
[4]?: {1} 'is 1' 'is not 1'
is 1
[5]?: {get-process nonexisting -ea 0} 'process exists' 'process doesn''t exist'
process doesn't exist

[6]function * { '*'*10 }
[7]function = { Set-Variable -scope Global -Name $args[0] -Value $args[1] }
[8]= a 100; $a
[9]$a = 200; $a #still works

Last example is tip by Johannes Rössel. He uses just Ctrl+D, Enter to exit Posh session. No more exit.

[10]# let's define function with name CTRL+D
[11]New-Item -Path "function:$([char][int]4)" -ItemType function -Value { exit }

Meta: 2010-05-04, Pepa