Monday, April 14, 2008

Creating arrays

In PowerShell an array can be contructed in a number of ways:

$a = 1, 2, 3, 4, 5
$a = 1..5

The "1..5" notation builds a range of numbers starting with 1 and ending with 5. It is also possible to create a decrementing list:

$a = 5..1
$a
5
4
3
2
1

As a server/network/database administrator one will often have to deal with servers/databases/tables/etc. that share the same name, except for some sort of numbering scheme:

WebServer001_HQ
WebServer002_HQ
..
WebServer064_HQ


If the above range is needed in PowerShell, it can easily be constructed:

1..64 | ForEach-Object{"WebServer{0:000}" -f $_ + "_HQ"}


What if there are "holes" in the number ranges? Well, ranges can easily be constructed using
"+". Lets make a server list including servers numbered from 4 to 30, but say the servers numbered 19-21 have been decommissioned, and two servers additional servers have been added, numbered 117 and 666:

4..18 + 22..30 + 117,666 | ForEach-Object{"WebServer{0:000}" -f $_ + "_HQ"}

WebServer004_HQ
WebServer005_HQ
WebServer006_HQ
WebServer007_HQ
WebServer008_HQ
WebServer009_HQ
WebServer010_HQ
WebServer011_HQ
WebServer012_HQ
WebServer013_HQ
WebServer014_HQ
WebServer015_HQ
WebServer016_HQ
WebServer017_HQ
WebServer018_HQ
WebServer022_HQ
WebServer023_HQ
WebServer024_HQ
WebServer025_HQ
WebServer026_HQ
WebServer027_HQ
WebServer028_HQ
WebServer029_HQ
WebServer030_HQ
WebServer117_HQ
WebServer666_HQ

No comments: