Prof. Powershell

PowerShell Syntax Part 2: Square Brackets

In the second part of this three-part series, the Prof. PowerShell breaks down how brackets should and shouldn't be used.

In the last lesson I tried to demystify when to use parentheses in PowerShell. Hopefully you understand at least the concept. Today we will look at square brackets []. Like parentheses, think of the brackets as holding something, but let's say in a more rigid manner. One way that you often see them used is with arrays.

An array is simply a collection of things. They might be usernames, services or processes. Using square brackets, we can access specific elements of the array by their index number.

PS C:\> $a = 1..10

Using the range operator ( .. ) I created a variable $a with the numbers 1 to 10. Using [] and an index number I can get specific element in the array.

PS C:\> $a[3]
4

Remember, arrays start counting at 0.

PS C:\> $a[0]
1

There's no period because this isn't a property or method. There's no parentheses because I'm not grouping or really doing anything with the index number. All I'm telling PowerShell is to show me a particular element in the array. By the way, you can use the range operator or a comma separated list of index numbers.

PS C:\> $a[0..2]
1
2
3

PS C:\> $a[2,4,6]
3
5
7

Some people get creating with [] and take advantage of the pipeline.

PS C:\> $svc = Get-Service
PS C:\> $svc[-2].RequiredServices[0]

Status   Name               DisplayName                          
------   ----               -----------                          
Running  wcmsvc             Windows Connection Manager

$Svc is an array of service objects. I'm getting the 2nd to last object and then displaying the first object in the RequiredServices property, which is a collection of service objects. This can get a little confusing because you can get an item as I've shown you:

PS C:\> $svc[2]

Status   Name               DisplayName                          
------   ----               -----------                          
Stopped  AllUserInstallA... Windows All-User Install Agent

Or like this:

PS C:\> $svc.Item(2)

Status   Name               DisplayName                           
------   ----               -----------                          
Stopped  AllUserInstallA... Windows All-User Install Agent  

In this situation, Item is a parameterized property which needs a value which is "held" by the parentheses. Personally, I think the first method is better and easier to understand (eventually).

You will also see brackets used to access elements in a hash table, which is a special type of array. Let me quickly create one.

PS C:\> $hash = @{Name="Jeff";Color="Green";Title="Professor"}

Normally, the easy way to access an element is by using the key as a property.

PS C:\> $hash.name
Jeff

However, this syntax also works.

PS C:\> $hash["name"]
Jeff

Where this comes in handy is with hash tables with more complex keys, i.e. those with spaces or characters. In those situations, this works much easier.

PS C:\> $svchash = get-ciminstance win32_service | group startName -AsHashTable
PS C:\> $svchash["nt authority\networkservice"]

Here's the result:

[Click on image for larger view.]  Figure 1.

You can get the same result:

PS C:\> $svchash."nt authority\networkservice

But this might be a little trickier to get right, especially for beginners. I'm not sure there really is a "right" way so you need to learn to interpret the use [] in context. Which brings us to the last way [] are used and that is to define .NET classes or types. When PowerShell sees [datetime] it knows that is a .NET class.

PS C:\> $x=5.1234
$x -as [int]
5

Here I told PowerShell to treat $X as an integer. Again, think of the brackets as unchanging. If you used (), PowerShell will try to evaluate what it is "holding".

[Click on image for larger view.]  Figure 2.

Although, oddly enough this actually works, although I wouldn't recommend it.

PS C:\> $x -as ('int')
5

Here's one more example.

PS C:\> [math]::Round($x,2)
5.12

[System.Math] indicates the .NET math class. The :: is the static method operator. In this example I'm invoking the Round() method. This method can take parameters which is why they are held in parentheses. I am rounding $x to 2 decimal places.

Allow me to leave you with a little homework. You should be able to run this command.

[math]::Round(((get-process)[3].WorkingSet/1MB),2)

Can you understand what the [] and () are doing? Next time we'll look at braces.

About the Author

Jeffery Hicks is an IT veteran with over 25 years of experience, much of it spent as an IT infrastructure consultant specializing in Microsoft server technologies with an emphasis in automation and efficiency. He is a multi-year recipient of the Microsoft MVP Award in Windows PowerShell. He works today as an independent author, trainer and consultant. Jeff has written for numerous online sites and print publications, is a contributing editor at Petri.com, and a frequent speaker at technology conferences and user groups.

comments powered by Disqus
Most   Popular