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 for me it has to be how everything in PowerShell is an object. It’s how you can build Really Cool Stuff from lots of simpler parts.
The typical way to start computer tutorials is with Hello World. And I’m nothing if I’m not a traditionalist;
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;
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;
($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;
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;
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;
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.