Working with PowerShell Objects Via Variables

One good fact to remember is that variables point to objects. Knowing this, one can simply treat the variable as the object itself. In this tutorial, you will learn how to work with objects through variables in PowerShell.

Setup

If you have not already done so, click open Windows PowerShell ISE.

Step one.

There are many ways in which one can manipulate the objects. The simplest object to deal with and the one we are going to be working with in this tutorial is a string.

The following code displays, Dan Daman:

Example

$firstname = "Dan"
$lastname = "Daman"
$fullname = $firstname + " " + $lastname
write-output $fullname
    

Copy and Try it

The output will be presented like the following:

Let us manipulate the text so that all characters are displayed in uppercase. String objects have a method called ToUpper() that returns the object in all uppercase letters.

The transformation is typed as follows:

Example

$firstname = "Dan"
$lastname = "Daman"
$fullname = $firstname + " " + $lastname
Write-output "Length of full name: " + $fullname.length
Write-output "Full name is: " + $fullname.ToUpper()
    

Copy and Try it

The output will be presented like the following:

Notice how parenthesis were not used for length but were definitely used for ToUpper. The reason behind this is because properties are directly available values, while ToUpper is an actual method that needs to be called. The dot between $fullname an ToUpper(), is used to tell PowerShell that whatever is after the period is the property of the method of whatever is before the period. Think of it as "owner.owned".

Step two.

Objects are instances of classes. Classes can be thought of as definitions, schemas or types. They define what objects are to look like. Because an object is an instance of a class, an instance of a class Dog might be your neighbour's dog Fifi. In a virtual world, an object is the instance of a class that you may interact with. Object properties are directly accessible while methods are not, they do something rather than just get an internally stored value. The ToUpper method above does not contain any value within the parenthesis because it does not require any parameters, however, in some instances, you will need parameters for method calls.

The following is an example of a method call with parameters:

Example

$fullname = "Johnny Tallman"
$newname = $fullname.replace("Tall", "Short")
write-output $newname
    

Copy and Try it

The output is presented as follows:

As you see, Tall was replaced with short. If the name were to be Tall Tallman, the method would change it to: Short Shortman.

Remarks last but not least…

Methods and objects are used quite frequently throughout PowerShell scripting, you can even create your own method and objects. We discuss this in future tutorials. Join us next time for additional Windows PowerShell tutorials