Powershell Simplified Part 3: Variables and Objects

Powershell creates new variables automatically, so there is no need to ‘declare’ them. Variable names are case-insensitive.

$val1 = 10                     # declare and assign a variable 
($val1).GetType().Name         # type is Int32
$val1 = “Hello”                # reassign the variable
($val1).GetType().Name         # type is String
[int]$val2 = 10                # strongly typed variable 
#$val2 = “Hello”               # throws error - cannont be assigned to string 

Powershell supports all .NET data types, this is very useful because you get access to all the type’s properties and methods…

# a simple XML string
$a = "<books><book name='1984' author='Orwell'/><book name='Macbeth' author='Shakespeare'/></books>"  
[xml]$booksXML = $a             # cast string to XML ('booksXML' is of type XML)
$booksXML.books.book            # Now we can XPATH into the XML

There’s also a different way to create a variable, by creating a variable object,

New-Variable val3 -value 10                  # a different way to create a variable 
$val3 = 5                                    # this can be reassigned
New-Variable val4 -value 10 -option ReadOnly # also see '-option Constant'
$val4 = 5                                # throws error: val4 cannot be reassigned 

Powershell provides access to some Windows environment variables for your convenience,

Get-Childitem env:            # get the full list
# or you could iterate over each element...
Get-Childitem env: | ForEach-Object {"{0} : {1}" -f $_.Name,$_.Value} 
write-host $env:OS            # or get individual members
write-host $env:windir 

Powershell has powerful (no pun intended) support for objects. One of the best parts about Powershell is that you can use all your regular .NET classes!

# In C#, string combined = System.IO.Path.Combine(path1, path2);
$combined = [System.IO.Path]::Combine($path1, $path2)

# In C#, string hostname = System.Net.Dns.GetHostName();
$hostname = [System.Net.Dns]::GetHostName()

# In C#, byte[] converted = Convert.FromBase64String(encrypted);
$converted = [Convert]::FromBase64String($encrypted)

# Let's go one step furhter and load a .NET assembly,
[void][reflection.assembly]::LoadWithPartialName("Microsoft.VisualBasic")

# What static types did we just load?
[Microsoft.VisualBasic.Interaction] | Get-Member -static

# Great! Let's use some,
[microsoft.VisualBasic.Interaction]::MsgBox("Hello VB!")
$name = [microsoft.VisualBasic.Interaction]::InputBox("Enter Name", "Name", "$env:username")
write-host "User typed:" $name

That was fun, now let’s create some objects in Powershell.

# First let's instantiate a .NET type with new-object,
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.Web.Administration") > $null
$iis = new-object Microsoft.Web.Administration.ServerManager 
$appPools = $iis.ApplicationPools 
foreach($app in $appPools)  { write-host $app.Name "is" $app.State } 

# Now let's create an object in Powershell,
$myObj = new-object Object
add-member -inputobject $myObj -membertype noteproperty -name Color -Value Red
add-member -inputobject $myObj -membertype noteproperty -name OS -Value $env:OS
add-member -inputobject $myObj -membertype scriptmethod -name SetColor( { param($color) $this.Color = $color } )
# To see what the args mean use: get-help add-member -full 

write-host "Color is: " $myObj.Color                        # Get the Color property
$myObj.Color = "Orange"                                     # Set the Color property
write-host "Color is: " $myObj.Color
write-host "Color type is: " $myObj.Color.GetType().FullName    # Property type is System.String by default
$myObj.SetColor("Blue")                                     # Set the property using a method 
write-host "Color is: " $myObj.Color

Powershell Simplified Part 2: Arrays and Hashtables

Today we’ll do some Powershell programming using some basic constructs. First let’s take a look at arrays in Powershell, turns out they are not much different from arrays in C#.

Try out these in a PS1 file (to run the ps1 file see the instructions in Part 1 of this series),

$array = @(1, "Hello", 3.14)                     # create a mixed Powershell array 
write-host “array length is” $array.length       # output the length of the array 
$array += "World"                                # append to the array  
write-host “third element is” $array[2]          # get the 3rd element in the array $array[3] = "Powershell"                         # update an element in the array $array = $array | Sort-Object                    # sort the array write-host “sorted array:” $array           # sorted array: 1 3.14 Hello Powershell $array = $array[0..1] + $array[3]           # remove the 3rd element from the array write-host $array $array = @()                                     # clears the array

Use foreach to loop through the array: foreach ($element in $array) { write-host $element }
Search the array for an item: $array –contains “2.18” (this evaluates to false in our case)
We can also wildcard search for an item: $array –like “He” (this evaluates to true in our case)

A hashtable also works as you would expect in Powershell,

$htable = @{UK = "London"; Austria = "Vienna"; France = "Paris"} # create a hashtable 
write-host $htable["UK"]                       # get the value of a key 
write-host $htable.France                      # another way to get a value 
write-host $htable.keys                        # get all the keys 
$htable["US"] = "Washington D.C."              # insert or update a key 
$htable.add("India", "New Delhi")              # another way to insert 
$htable.remove("UK")                           # remove a key 
foreach ($key in $htable.keys) { write-host $key ":" $htable[$key] }   # enumerate

Use ContainsKey or ContainsValue to search inside the hashtable: $hashtable.ContainsKey("India")

Powershell Simplified Part 1: Basics

You can start the Powershell command line by opening the cmd window and typing ‘powershell’.
Alternately, you can click on the Powershell icon or search for Windows Powershell in the StartMenu.

To check what Powershell version you’re running type $host.

image

See all the built-in commands Powershell provides: get-command
You can also filter to get a subset of the commands: get-command get-*
To filter by CommandType: get-command –commandtype cmdlet

To get more information on how to use a particular command you can use get-help: get-help get-date
Or simply add a –? at the end of a command: get-eventlog –?

Let’s try out some simple commands at the Powershell command prompt. These should be self explanatory.

get-process
get-date
start-process notepad

Now let’s try some basic scripting. Create a document called say test.ps1, and copy the three commands into the file. At the Powershell prompt go to the folder which has this file (using the regular cd command – if you notice cd is defined as an alias in Powershell, check using ‘cd –?’). Then type the following at the prompt (note the dot and slash before the file name).

PS C:\> .\test.ps1

You should see the output on the console window and a new notepad instance.

Powershell Simplified Series

I’ve been using Powershell for sometime now for various small tasks. Powershell is a command line based scripting language designed for system admin tasks in Windows. It’s quite powerful and can help you deploy code, analyze logs, and perform remote machine operations among others tasks. The Scripting Guy blog is the best Powershell blog I’ve found.

Powershell Simplified Part 1: Basics
Powershell Simplified Part 2: Arrays and Hashtables
Powershell Simplified Part 3: Variables and Objects
Powershell Simplified Part 4: Registry and Processes
Powershell Simplified Part 5: Services and EventLogs
Powershell Simplified Part 6: Functions
Powershell Simplified Part 7: Error Handling
Powershell Simplified Part 8: Accessing the File System
Powershell Simplified Part 9: Powershell Tips
Powershell Simplified Part 10: WMI