oreilly.comSafari Books Online.Conferences.


AddThis Social Bookmark Button

Top 10 Tips for Using Windows PowerShell
Pages: 1, 2, 3, 4, 5

3. Learn the fundamental types and built-in variables

Learn the fundamental types and how the parser recognizes them. Master regular expressions so your life will be complete.

The PowerShell scripting language includes several basic types that are useful in your work. And, you can create variables of these types. You have at your disposal all the built-in types in .NET. This includes, for example, strings, numbers, arrays, and dictionaries (which some people know as hashes or maps). The types are all built around the .NET types. (I talk about .NET in the next section.)

The command parser will decide the types based on what you type. For example, if you type


you will be specifying an integer. Variable names get a $ before them, and you can store the integer like so:

PS C:\> $a = 5
PS C:\> $a
PS C:\>

You can determine the built-in .NET type by calling GetType():

PS C:\> $a.GetType()
IsPublic IsSerial Name              BaseType
-------- -------- ----              --------
True     True     Int32             System.ValueType

The parser also recognizes other basic types. Doubles can be created with a decimal point:

PS C:\> $b = 3.1415926
PS C:\> $b
PS C:\> $b.GetType().Name

Like many of today's scripting languages, you can use either single or double quotes for strings, whichever is convenient for the problem at hand. For example, if you need double-quotes in the string, you can use single quotes for the string itself:

$c = '<span style="border:1px solid none">'

To create an array, just provide a list of comma-separated items:

PS C:\> $d = 1,2,3,"Hello"
PS C:\> $d
PS C:\> $d.GetType()

IsPublic IsSerial Name                                     BaseType
-------- -------- ----                                     --------
True     True     Object[]                                 System.Array

If necessary, you can put parentheses around the array. This is useful for arrays of arrays:

$e = (1,2,3,(4,5,6))

You can specify ranges of integers using the .. operator like so:

$f = 1..5

will create an array containing 1,2,3,4,5.

To create a dictionary, use the @ symbol like so:

PS C:\> $myhash = @{ 'one'=1; 'two'=2; 'three'=3 }
PS C:\> $myhash

Name                           Value
----                           -----
two                            2
three                          3
one                            1

PS C:\> $myhash['one']
PS C:\> $myhash['four']
PS C:\>

Since .NET includes powerful regular expression capabilities, PowerShell includes a regex type. Just put the word regex in brackets ([]) before a string to create a regular expression. Then you can use the regular expression with the -match operators. Here's an example:

PS C:\> $re = [regex]"abc[123]"
PS C:\> "abc1" -match $re
PS C:\> "abc4" -match $re
PS C:\>

If you're not familiar with regular expressions, then now is a great time to learn them. The more you know regular expressions, the easier time you'll have with PowerShell as well as many programming languages. Go to your favorite search engine and type in "learn regular expressions". There are several good pages out there. But probably the best source is the O'Reilly book Mastering Regular Expressions by Jeffrey Friedl. This is one of the few books that should be required reading for every computer professional.

The shell includes some built-in variables that you can use, too. Here are some of them:

  • $$: Last token of previous line
  • $?: Last success/fail status
  • $^: First token of previous line
  • $pshome: The installation directory of PowerShell. This is useful if you're going to modify some of the configuration files, such as types.ps1xml, like so:

    scite (join-path $pshome types.ps1xml)

(Scite is the free text editor I use.)

If you want to use a specific type without relying on the parse, PowerShell comes with several built-in type shortcuts. A type shortcut is a shortened form of a type name. The Microsoft PowerShell's blog includes an entry listing some of them.

Learning and understanding the types can be unwieldy, however, especially if a command returns an object of a type you're not familiar with. If you're savvy with reading online helps, this blog entry is a way to enhance your PowerShell so you can access the online help for any object's type.

(If you make this change, you'll have to re-sign your file. See the tip "Customize your environment" for more information.) When you implement this modification, you can find the online help for any object's type. The technique isn't perfect and doesn't work for every object, but it does work most of the time.

4. Know your .NET

The .NET framework is the foundation on which PowerShell runs. The more you know about .NET, the better your PowerShell experience will be.

To get the most out of PowerShell, you should be familiar with the .NET framework. The framework's help is available online in its entirety at . Scroll down to the System heading. This is where you'll find the basic types such as Int32, String, and Array.

Remember, the framework is simply a huge collection of classes and types that you can use in your PowerShell work. The more you know of these types, the better off you are. If you look up entries on your types, you'll know what you can do with objects. For example, if you click the page for System, scroll down and click String, you'll get the entry for the String class.

Most of the commands return an object (or a set of objects) that are, in fact, .NET objects. For example, the Get-Date command on the surface may appear to just print out the current date and time. But in fact, it returns an object of type DateTime, which is part of the .NET framework. Similarly, if you type Get-ChildItem (or an alias, dir), you see a directory listing, but in fact, are looking at a list of objects, each of which is either a DirectoryInfo or a FileInfo object. These are .NET classes.

The .NET framework is organized into a huge hierarchy, with all classes being derived from Object. The Object class provides some base functionality common to every single class in .NET. One base functionality is a function called ToString. This function returns a text representation of an object. The way this pertains to PowerShell is that given any object, you can always get a string representation of it. (In fact, this is exactly how PowerShell prints out an object to the console.)

Pages: 1, 2, 3, 4, 5

Next Pagearrow