PowerShell: Tutorial 1, Everything is an Object

A series of tutorials, or How To Get Started With PowerShell:  “It’s Awesome” edition.

When I thought about what I considered the most important, fundamental thing to learn about PowerShell I went through a couple of options;  Piping?  The help system and Get-Command?  -WhatIf?

All useful things to learn but it has to be how everything in PowerShell is an object.  It’s how you can build Really Cool Stuff from lots of simple bits and it’s also the thing that catches me out occasionally.

The typical way to start computer tutorials is with Hello World.  And I’m nothing if I’m not a traditionalist;1

Which works, as you’d expect;  it writes “Hello World” directly to the host (your screen).

However the general recommendation is not to use Write-Host.  Instead we should write it as an object, using Write-Output;2

It looks about the same, right?  So what’s the difference?

PowerShell treats everything as an object until it gets written to the screen.  And if you just give PowerShell an object it’ll just write it to the screen for you;3

($Hello is a variable;  use them to store objects.  You refer to variables with the “$” prefix)

So don’t worry about outputting things, let PowerShell do it for you.

Once you’ve got an object there’s all sorts of things we can do with it too.

You can see what you can do to a particular object by piping it to Get-Member;

$Hello | Get-Member

(The “|” is the pipe symbol.  You can use it to join multiple cmdlets together to do cool stuff)

For a piece of text there’s quite a bit;4

If I wanted to do something I’d just look at what Get-Member told me and pick what’s closest to what I want to do.  Splitting a string or making it all upper case, for example;5

Each object will have a Type to it.  “Hello World!” was a string of characters (or string for short).  String objects have the properties and methods (information you can get or stuff you can do) as above.  But objects of a different type will give you different options;6

No point having a ToUpper() for numbers but ToDecimal() might be more useful!

This is why the recommendation is to keep things as objects for as long as possible and not to write things to the screen as strings;  when they’re objects you get Type-specific commands you can use.  Once it’s written to a string (to the screen for example) you’re restricted to only the string commands.

 

 

 

 

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