Arrays


An array is essentially a container for storing things. For almost all administrative scripts, simple arrays will suffice. When you think about a simple array, picture an egg carton with a single row. You can make the egg carton as long as you want. With a simple array, you can put numbers, strings, or objects in each compartment. Multi-dimensional arrays exist, but they are beyond the scope of what we want to cover here.

Array or Collection

When reading technical material, you may also come across the term collection, which is a type of array that is usually created as the result of some query. For example, you might execute a query to return all instances of logical drives on a remote server using Windows Management Instrumentation (WMI). The resulting object will hold information about all logical drives in a collection. This collection object is handled in the much same way as an array when it comes time to enumerate the contents. For now, remember that when you see the term collection - think array.

You can create an array by defining a variable and specifying the contents:

 PS C:\> $a=9,5,6,3 

To view the contents of $a, all you need to do is type $a:

 PS C:\> $a 9 5 6 3 

The other technique you are more likely to use is the ForEach cmdlet:

 PS C:\> foreach ($i in $a) {Write-host $i} 9 5 6 3 PS C:\> 

This cmdlet looks inside the parentheses for what it should process. For every item in the parentheses, the ForEach cmdlet does whatever commands are in the curly braces. In the previous example we used a variable name of $i. This example instructs the ForEach cmdlet that for every $i variable in the $a variable, our array, it should echo back the value of $i.

When we run this command the first time, the cmdlet gets the first value of the array ($a) and sets it to $i. The cmdlet writes the value of $i to the console, and then runs through the array again getting the next array element, 5. This process is repeated until the end of the array is reached.

If you want to create an array with a range of numbers, you should use the range operator ():

 PS C:\> $a=2..7 PS C:\> $a 2 3 4 5 6 7 PS C:\> 

To create an array with strings, each element must be enclosed in quotes:

 PS C:\> $servers="dc1","app02","print1","file3" PS C:\> foreach ($c in $servers) {$c} dc1 app02 print1 file3 PS C:\> 

If you used $servers="dc1,app02,print1,file3" then the only element of the array would be dc1,app02,print1,file3, because PowerShell only sees one set of double quotes. Therefore, there will be only one item to make into an array.

PowerShell arrays can also contain objects. Consider this example:

 PS C:\> $svc=get-service | where {$_.status -eq "running"} PS C:\> $svc Status   Name               DisplayName ------   ----               ----------- Running  AudioSrv           Windows Audio Running  Avg7Alrt           AVG7 Alert Manager Server Running  Avg7UpdSvc         AVG7 Update Service Running  AVGEMS             AVG E-mail Scanner Running  CryptSvc           Cryptographic Services Running  DcomLaunch         DCOM Server Process Launcher Running  Dhcp               DHCP Client Running  Dnscache           DNS Client Running  Eventlog           Event Log Running  EventSystem        COM+ Event System Running  IISADMIN           IIS Admin Running  iPodService        iPodService Running  lanmanserver       Server [remaining output truncated] 

We've created an array called $svc that contains all running services. We'll work with this more a little later.

When you work with individual elements in an array, the first important thing to remember is that arrays start counting at 0. To reference a specific element the syntax is $arrayname[index]:

 PS C:\> write-host $servers[0] dc1 PS C:\> write-host $servers[3] file3 PS C:\> 

You can use the length property of the array to determine how many elements are in the array:

 PS C:\> $servers.length 4 PS C:\> 

If you go back and look at the contents, you'll see that file3 is the last element of the array, yet it has an index of [3]. What gives? Remember to start counting at 0.

It's also easy to create an array from an existing source instead of manually typing a list of names. If you already have a list of server names such as Servers.txt, you could read that file with the Get-Content cmdlet and populate the array:

 PS C:\> $Serverlist =get-content servers.txt PS C:\> $serverlist Seattle1 Vegas02 XPLAP01 PS C:\> 

In this example servers.txt is a simple text file with a list of computer names. We create the array $serverlist by invoking Get-Content. Invoking $serverlist merely displays the array's contents. Armed with this array, it's a relatively simple matter to parse the array and pass the computer name as the parameter for any number of commands:

 PS C:\> foreach ($srv in $serverlist) { >> write-host "Examining" $srv >> #calling get-wmiobject >> get-wmiobject -class win32_operatingsystem -computername $srv >> } >> Examining Seattle1 get-wmiobject : The RPC server is unavailable. (Exception from HRESULT: 0x80070 6BA) At line:4 char:14 + get-wmiobject  <<<< -class win32_operatingsystem -computername $srv Examining Vegas02 get-Wmiobject : The RPC server is unavailable. (Exception from HRESULT: 0x80070 6BA) Examining XPLAP01 SystemDirectory : C:\WINDOWS\system32 Organization    : MyCo BuildNumber     : 2600 RegisteredUser  : Admin SerialNumber    : 55274-640-1714466-23528 Version         : 5.1.2600 PS C:\> 

Using ForEach we enumerate each element of the array and execute two cmdlets. Write-Host is called to display a message about what PowerShell is doing. Then we call the Get-Wmiobject cmdlet to return operating system information from the specified server using WMI. In this particular example the cmdlet returned an error for some of the servers because they don't actually exist.



Windows PowerShell. TFM
Internet Forensics
ISBN: 982131445
EAN: 2147483647
Year: 2004
Pages: 289

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net