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
Advertisements

About soumya chattopadhyay
I live and work in Seattle, WA. I work with Microsoft technologies, and I'm especially interested in C#.

One Response to Powershell Simplified Part 3: Variables and Objects

  1. Pingback: Powershell Simplified Series « I.Net

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: