Welcome PowerShell User! This recipe is just one of the hundreds of useful resources contained in the PowerShell Cookbook.
If you own the book already, login here to get free, online, searchable access to the entire book's content.
If not, the Windows PowerShell Cookbook is available at Amazon, or any of your other favourite book retailers. If you want to see what the PowerShell Cookbook has to offer, enjoy this free 90 page e-book sample: "The Windows PowerShell Interactive Shell".
You want to access the elements of an array.
To access a specific element of an array, use PowerShell’s array access mechanism:
PS > $myArray = 1,2,"Hello World" PS > $myArray[1] 2
To access a range of array elements, use array ranges and array slicing:
PS > $myArray = 1,2,"Hello World" PS > $myArray[1..2 + 0] 2 Hello World 1
PowerShell’s array access mechanisms provide a convenient way to access either specific elements of an array or more complex combinations of elements in that array. In PowerShell (as with most other scripting and programming languages), the item at index 0 represents the first item in the array.
For long lists of items, knowing the index of an element can sometimes pose a problem. For a solution to this, see the Add-FormatTableIndexParameter
script included with this book’s code examples. This script adds a new -IncludeIndex
parameter to the Format-Table
cmdlet:
PS > $items = Get-Process outlook,powershell,emacs,notepad PS > $items Handles NPM(K) PM(K) WS(K) VM(M) CPU(s) Id ProcessName ------- ------ ----- ----- ----- ------ -- ----------- 163 6 17660 24136 576 7.63 7136 emacs 74 4 1252 6184 56 0.19 11820 notepad 3262 48 46664 88280 376 20.98 8572 OUTLOOK 285 11 31328 21952 171 613.71 4716 powershell 767 14 56568 66032 227 104.10 11368 powershell PS > $items | Format-Table -IncludeIndex PSIndex Handles NPM(K) PM(K) WS(K) VM(M) CPU(s) Id ProcessName ------- ------- ------ ----- ----- ----- ------ -- ----------- 0 163 6 17660 24136 576 7.63 7136 emacs 1 74 4 1252 6184 56 0.19 11820 notepad 2 3262 48 46664 88280 376 20.98 8572 OUTLOOK 3 285 11 31328 21952 171 613.71 4716 powershell 4 767 14 56568 66032 227 104.15 11368 powershell PS > $items[2] Handles NPM(K) PM(K) WS(K) VM(M) CPU(s) Id ProcessName ------- ------ ----- ----- ----- ------ -- ----------- 3262 48 46664 88280 376 20.98 8572 OUTLOOK
Although working with the elements of an array by their numerical index is helpful, you may find it useful to refer to them by something else—such as their name, or even a custom label. This type of array is known as an associative array (or hashtable). For more information about working with hashtables and associative arrays, see Recipe 7.13.
For more information on lists and arrays in PowerShell (including the array ranges and slicing syntax), see “Arrays and Lists”. For more information about obtaining the code examples for this book, see “Using Code Examples”.
Recipe 7.13, “Create a Hashtable or Associative Array”
“Arrays and Lists”