PowerShell has become one of the most popular scripting languages due to its object-oriented nature. Unlike traditional shells like Command Prompt and Bash which are text-based, PowerShell is built on top of the .NET framework and oriented around objects.

In PowerShell, everything is an object with properties that store information. Therefore, knowing how to retrieve and manipulate object properties is critical for unlocking the full potential of PowerShell.

In this comprehensive guide, you will learn:

  • What are objects and properties in PowerShell
  • How to use the Get-Member cmdlet to view object properties
  • Real-world examples of getting properties of different object types
  • Advanced techniques for filtering and selecting properties
  • How to extend objects with custom properties

So if you want to level up your PowerShell skills, keep reading!

What are Objects and Properties in PowerShell?

An object in PowerShell represents a real-world entity like a file, process, service etc. Objects have attributes called properties which define the characteristics of that object.

For example, a File object has properties like Name, Length, LastWriteTime etc. Similarly, a Process object has properties like ID, Name, WorkingSet etc.

When you execute commands in PowerShell, the output is returned as objects. For instance, the Get-Process commandlet returns a collection of System.Diagnostics.Process objects.

Understanding this object-based nature is the key that unlocks the full potential of PowerShell.

Introducing the Get-Member Cmdlet

The Get-Member cmdlet allows you to view all properties and methods of an object. It is one of the most useful commands for inspecting objects in PowerShell.

The basic syntax is:

Get-Member -InputObject <Object>

You can also pipe any object into Get-Member:

<Command> | Get-Member

Now let‘s look at some examples to understand this better.

Example 1: Getting Process Properties

The Get-Process commandlet returns a collection of System.Diagnostics.Process objects representing the running processes.

We can pipe the output of Get-Process into Get-Member to view the properties exposed by the Process object:

PS> Get-Process | Get-Member


   TypeName: System.Diagnostics.Process

Name                       MemberType     Definition                    
----                       ----------     ----------                    
Handles                    AliasProperty  Handles = Handlecount         
Name                       AliasProperty  Name = ProcessName            
NPM                        AliasProperty  NPM = NonpagedSystemMemorySize
PM                         AliasProperty  PM = PagedMemorySize          
VM                         AliasProperty  VM = VirtualMemorySize        
WS                         AliasProperty  WS = WorkingSet               
Disposed                   Event          System.EventHandler Disposed   
ErrorDataReceived          Event          System.Diagnostics.DataReceived...
Exited                     Event          System.EventHandler Exited     
OutputDataReceived         Event          System.Diagnostics.DataReceived...
BeginErrorReadLine         Method         void BeginErrorReadLine()     
BeginOutputReadLine        Method         void BeginOutputReadLine()    
CancelErrorRead            Method         void CancelErrorRead()        
CancelOutputRead           Method         void CancelOutputRead()       
Close                      Method         void Close()                  
CloseMainWindow            Method         bool CloseMainWindow()        
CreateObjRef               Method         System.Runtime.Remoting.ObjRef ...
Dispose                    Method         void Dispose(), void IDispos...
Equals                     Method         bool Equals(System.Object obj)
GetHashCode                Method         int GetHashCode()             
GetLifetimeService         Method         System.Object GetLifetimeServ...
GetType                    Method         type GetType()                
InitializeLifetimeService  Method         System.Object InitializeLifet...
Kill                       Method         void Kill()                   
Refresh                    Method         void Refresh()                
Start                      Method         bool Start()                  
ToString                   Method         string ToString()              
WaitForExit                Method         bool WaitForExit(int millise...
WaitForInputIdle           Method         bool WaitForInputIdle(int mi...
__NounName                 NoteProperty   string __NounName=Process     
BasePriority               Property       int BasePriority {get;}        
Container                  Property       System.ComponentModel.Contai...
EnableRaisingEvents        Property       bool EnableRaisingEvents {ge...
ExitCode                   Property       int ExitCode {get;}            
ExitTime                   Property       datetime ExitTime {get;}       
Handle                     Property       IntPtr Handle {get;}          
HandleCount                Property       int HandleCount {get;}        
HasExited                  Property       bool HasExited {get;}          
Id                         Property       int Id {get;}               
MachineName                Property       string MachineName {get;}      
MainModule                 Property       System.Diagnostics.ProcessMod...
MainWindowHandle           Property       IntPtr MainWindowHandle {get;}
MainWindowTitle            Property       string MainWindowTitle {get;}
MaxWorkingSet              Property       IntPtr MaxWorkingSet {get;set;}
MinWorkingSet              Property       IntPtr MinWorkingSet {get;set;}
Modules                    Property       System.Diagnostics.ProcessMod...
NonpagedSystemMemorySize   Property       int NonpagedSystemMemorySize...
NonpagedSystemMemorySize64 Property       long NonpagedSystemMemorySize... 
PagedMemorySize            Property       int PagedMemorySize {get;}     
PagedMemorySize64          Property       long PagedMemorySize64 {get;}  
PagedSystemMemorySize      Property       int PagedSystemMemorySize {g...
PagedSystemMemorySize64    Property       long PagedSystemMemorySize64...
PeakPagedMemorySize        Property       int PeakPagedMemorySize {get;} 
PeakPagedMemorySize64      Property       long PeakPagedMemorySize64 {...
PeakWorkingSet             Property       int PeakWorkingSet {get;}      
PeakWorkingSet64           Property       long PeakWorkingSet64 {get;}   
PriorityBoostEnabled       Property       bool PriorityBoostEnabled {g...
PriorityClass              Property       System.Diagnostics.ProcessPri...  
PrivateMemorySize          Property       int PrivateMemorySize {get;}   
PrivateMemorySize64        Property       long PrivateMemorySize64 {ge...
PrivilegedProcessorTime    Property       timespan PrivilegedProcessor...
ProcessName                Property       string ProcessName {get;}      
ProcessorAffinity          Property       System.IntPtr[] ProcessorAff...
Responding                 Property       bool Responding {get;}         
SafeHandle                 Property       Microsoft.Win32.SafeHandles...
SessionId                  Property       int SessionId {get;}           
Handle                      ScriptProperty System.Object Handle {get=$...
NPM                         ScriptProperty System.Object NPM {get=$this...
PM                          ScriptProperty System.Object PM {get=$this....
StartTime                   Property       datetime StartTime {get;}      
SynchronizingObject         Property       System.ComponentModel.ISynco...
Threads                     Property       System.Diagnostics.ProcessTh...
TotalProcessorTime          Property       timespan TotalProcessorTime... 
UserProcessorTime           Property       timespan UserProcessorTime ...
VirtualMemorySize           Property       int VirtualMemorySize {get;}  
VirtualMemorySize64         Property       long VirtualMemorySize64 {g...
WorkingSet                  Property       int WorkingSet {get;}         
WorkingSet64                Property       long WorkingSet64 {get;}
Site                        Property       System.ComponentModel.ISite...
Container                   Property       System.ComponentModel.ICont... 

As you can see, the Get-Process object exposes a ton of useful properties like ID, Name, CPU times, Memory usage etc. This allows us to gather detailed insights into running processes.

Now let‘s look at how to get properties of other common object types in PowerShell.

Example 2: Getting File/Folder Properties

The Get-ChildItem commandlet returns System.IO.FileInfo and System.IO.DirectoryInfo objects representing files and folders.

We can use Get-Member to reveal their properties:

PS> Get-ChildItem | Get-Member


   TypeName: System.IO.DirectoryInfo

Name                      MemberType            Definition                   
----                      ----------            ----------                   
Create                    Method                System.IO.DirectoryInfo Cre...
CreateObjRef              Method                System.Runtime.Remoting.Obj... 
CreateSubdirectory        Method                System.IO.DirectoryInfo Cr...
Delete                    Method                void Delete(), void Delete...
Equals                    Method                bool Equals(System.Object ...
GetAccessControl          Method                System.Security.AccessCont...
GetDirectories            Method                System.IO.DirectoryInfo[] ...
GetFiles                  Method                System.IO.FileInfo[] GetFi...
GetFileSystemInfos        Method                System.IO.FileSystemInfo[]...
GetHashCode               Method                int GetHashCode()            
GetLifetimeService        Method                System.Object GetLifetimeS...
GetObjectData             Method                void GetObjectData(System....
GetType                   Method                type GetType()               
InitializeLifetimeService Method                System.Object InitializeLi... 
MoveTo                    Method                void MoveTo(string destDirName) 
Refresh                   Method                void Refresh()               
ToString                  Method                string ToString()             
Encrypt                   Method                void Encrypt()               
Decrypt                   Method                void Decrypt()               
__NounName                NoteProperty          string __NounName=Directory  
Exists                    Property              bool Exists {get;}            
Attributes                Property              System.IO.FileAttributes A...
CreationTime              Property              datetime CreationTime {get;}  
CreationTimeUtc           Property              datetime CreationTimeUtc {...  
Extension                 Property              string Extension {get;}       
FullName                  Property              string FullName {get;}        
LastAccessTime            Property              datetime LastAccessTime {g... 
LastAccessTimeUtc         Property              datetime LastAccessTimeUt...  
LastWriteTime             Property              datetime LastWriteTime {g...   
LastWriteTimeUtc          Property              datetime LastWriteTimeUt...    
Name                      Property              string Name {get;}            
Parent                    Property              System.IO.DirectoryInfo P...  
Root                      Property              System.IO.DirectoryInfo R...   


   TypeName: System.IO.FileInfo

Name                      MemberType Definition                   
----                      ---------- ----------                   
AppendText                Method     System.IO.StreamWriter Append...
CopyTo                    Method     System.IO.FileInfo CopyTo(str...  
Create                    Method     System.IO.FileStream Create()  
CreateObjRef              Method     System.Runtime.Remoting.ObjRef ...
CreateText                Method     System.IO.StreamWriter Create...
Decrypt                   Method     void Decrypt()               
Delete                    Method     void Delete(), void Delete...
Encrypt                   Method     void Encrypt()                     
Equals                    Method     bool Equals(System.Object obj)
GetAccessControl          Method     System.Security.AccessControl....
GetHashCode               Method     int GetHashCode()             
GetLifetimeService        Method     System.Object GetLifetimeServ...
GetType                   Method     type GetType()                
InitializeLifetimeService Method     System.Object InitializeLifet...
MoveTo                    Method     void MoveTo(string destFileName)
Open                      Method     System.IO.FileStream Open(Syst...
OpenRead                  Method     System.IO.FileStream OpenRead()  
OpenText                  Method     System.IO.StreamReader OpenTex...  
OpenWrite                 Method     System.IO.FileStream OpenWrite() 
Refresh                   Method     void Refresh()                
Replace                   Method     System.IO.FileInfo Replace(st...
ToString                  Method     string ToString()              
__NounName                NoteProperty string __NounName=File     
Attributes                Property   System.IO.FileAttributes Attri...
CreationTime              Property   datetime CreationTime {get;} 
CreationTimeUtc           Property   datetime CreationTimeUtc {ge...
Directory                 Property   System.IO.DirectoryInfo Direc...  
DirectoryName             Property   string DirectoryName {get;}    
Exists                    Property   bool Exists {get;}             
Extension                 Property   string Extension {get;}        
FullName                  Property   string FullName {get;}         
IsReadOnly                Property   bool IsReadOnly {get;}          
LastAccessTime            Property   datetime LastAccessTime {get;...
LastAccessTimeUtc         Property   datetime LastAccessTimeUtc {g... 
LastWriteTime             Property   datetime LastWriteTime {get;s...
LastWriteTimeUtc          Property   datetime LastWriteTimeUtc {ge...
Length                    Property   long Length {get;}             
Name                      Property   string Name {get;}  

The objects returned by Get-ChildItem contain properties like Name, Length, various timestamps etc. These can be used to gather insights about files and folders.

Now that you‘ve seen some examples, let‘s go over some advanced techniques related to getting object properties in PowerShell.

Filtering Properties with Select-Object

While Get-Member shows all properties, we often need only specific properties. The Select-Object cmdlet allows us to filter properties easily:

Get-Process | Select-Object -Property Id, Name, CPU

This returns the Id, Name and CPU usage properties for all processes.

You can also exclude properties using the -ExcludeProperty parameter:

Get-Process | Select-Object * -ExcludeProperty Path 

This returns all properties except the Path.

Calculating Properties with Select-Object

Select-Object also allows you to calculate custom properties.

For example, to add a PercentCPU property showing the percentage CPU usage:

Get-Process | Select-Object Name, 
    @{Name=‘PercentCPU‘;Expression={$_.CPU / $_.TotalProcessorTime.TotalSeconds * 100}}

You can calculate advanced metrics this way for better analysis.

Selecting Properties by Name with Where-Object

The Where-Object cmdlet allows you to filter objects based on property values.

For example to get only processes named explorer:

Get-Process | Where-Object Name -eq explorer

Where-Object gives you precise control over which objects are returned based on property conditions.

Extending Objects with Add-Member

You can even add custom properties to existing objects using Add-Member:

Get-Process | Add-Member -Name PercentCPU -Value {$_.CPU / $_.TotalProcessorTime.TotalSeconds * 100} -PassThru  

This dynamically extends Process objects to have a PercentCPU property without needing Select-Object.

Add-Member allows you create enriched objects tailored to your needs.

Summary

That covers the main techniques related to getting and manipulating object properties in PowerShell!

The key takeaways are:

  • Get-Member reveals properties of output objects
  • Select-Object filters properties and creates custom ones
  • Where-Object selects objects based on property conditions
  • Add-Member dynamically extands objects with new properties

I hope you now feel empowered to unlock the hidden potential within PowerShell objects! Let me know in the comments if you have any other questions.

Similar Posts