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 chosen will be displayed in the order you specify with Select-Object.

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:\> gci | gm -membertype NoteProperty
PS C:\> gci | 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 Commands:

Redirection - Spooling output to a file

Copyright © SS64.com 1999-2019
Some rights reserved