How-to: Some basic PowerShell principles - Objects, Methods and Properties

A key concept to grasp when starting to work in PowerShell is that everything is an object.

As a comparison example with the CMD shell, the old DIR command has a default output of:
Date Time <DIR> FileSize FileName

Because the output is plain text, you have virtually no choice about the output format, you can’t for example ask for just the FileNames followed by the Dates.

PowerShell in contrast will list files (or anything else) as an object, so Get-ChildItem has a default output of:
Mode LastWriteTime Size/Length Name

Those output items are just the default properties of the object, if they don’t happen to suit your purposes today, you can choose to return a different set of properties that you do want:

PS C:\> Get-ChildItem | Select-Object Name, LastWriteTime

# or in short format
PS C:\> gci | Select Name, LastWriteTime

PS C:\> $a = (Get-ChildItem c:\docs\sample.txt)
PS C:\> Write-Host $a.fullname $a.length $a.lastwritetime

The items will be displayed in the order of the Select-Object clause so if you wanted LastWriteTime to be shown first, just swap around the order.

What is an object?

An object has an object type (e.g. a file object is a FileInfo type, a registry location object is a PathInfo type)

An object has methods (e.g. a file object can be copied, a registry key has a value that can be deleted)

An object has properties (e.g. a file object has a FileSize and a DateModified, a memory process object has a PID and a MaxWorkingSet)

To list all this meta data for an object use the Get-Member command:

PS C:\> Get-ChildItem | Get-Member
PS C:\> Get-Process | Get-Member
PS C:\> Get-Location | Get-Member
PS C:\> Get-Service | Get-Member
PS C:\> $myobjectvariable | Get-Member

To narrow this down further you can choose to list only Methods, Properties or NoteProperties, NoteProperties are just properties inherited from the PowerShell environment:

PS C:\> Get-ChildItem | Get-Member -membertype method
PS C:\> Get-ChildItem | gm -membertype NoteProperty
PS C:\> Get-ChildItem | gm -membertype *property

Perform a method on an object like this:

PS C:\> $a=Get-ChildItem C:\MyDemoFile.txt
PS C:\> $a.get_lastAccessTime()
PS C:\> $a.gettype()
PS C:\> $a.MoveTo("c:\demo files\MyDemoFile.txt")

A method can also be used to take an action on a property value:

PS C:\> $a.name.ToUpper()

The ability to use object methods to take specific actions, and object properties to manipulate data becomes particularly useful when you start to combine multiple commands into a single pipeline.

“No object is so beautiful that, under certain conditions, it will not look ugly” ~ Oscar Wilde

Related PowerShell Cmdlets

Redirection - Spooling output to a file.


 
Copyright © 1999-2024 SS64.com
Some rights reserved