Working with Objects in PowerShell

Introduction: An object is an instance of type, many cmdlets are available to get details of an object, create new or update an existing object. In PowerShell, an object can be created either using type of .Net Framework class or with ProgID of a COM object which holds properties and methods

New-Object cmdlet: This cmdlet helps to create an new instance of type either for .Net framework class or using ProgID of a COM. Let’s see an example to create an object of the Excel application and add a new sheet to it.

#Example 1 : Open an excel and add a new sheet
$obj = New-Object -COMObject excel.application
$obj.visible = $True
$workbook = $obj.Workbooks.Add()

Get-Member cmdlet: This cmdlet retrieves the properties and method of an object. This cmdlet takes input object as parameter or pipe with an object to get member. To get member of a type, -MemberType is used and to get static members of an object use -static parameter. Let’s see some examples:

#Example 2 : This command gives typename and list of members in DirectoryInfo class

Get-Item 'C:\Program Files' | Get-Member

#Below commands list all the properties and methods of DirectoryInfo class
Get-Item 'C:\Program Files' | Get-Member -MemberType Properties
Get-Item 'C:\Program Files' | Get-Member -MemberType Methods

#Below command list only the static members of DirectoryInfo class
Get-Item 'C:\Program Files' | Get-Member -Static

#Below command list all the properties which can only set
Get-Item 'C:\Program Files' | Get-Member -MemberType Properties 
| Where-Object {$_.issettable} | Format-Table -Property name

Add-Member cmdlet: This cmdlet allows to add new properties and method to an instance object. Add-Member cmdlet used with Pipe and object or passing the parameter through InputObject.

#Example 3: Adds a IsReadable property to FileInfo Objects and prints the output
$obj = Get-ChildItem 'C:\temp\Test.txt'
$obj | Add-Member -NotePropertyName IsReadable -NotePropertyValue True

#Example 4: Add a method to FileInfo Object and call that method within is powershell

$F = Get-ChildItem C:\Temp\test.xlsx
$S = {[math]::Round(($this.Length / 1KB), 4)}
$F | Add-Member -MemberType ScriptMethod -Name "SizeInKB" -Value $S

What are supported Member Types: With Get-Member cmdlet -Member Type parameter is used to filter out the members and with Add-Member cmdlet, is used to add members based on the provided Member Types. List of supported member types are listed as below:

  • AliasProperty
  • CodeProperty
  • Property
  • NoteProperty
  • ScriptProperty
  • PropertySet
  • Method
  • CodeMethod
  • ScriptMethod
  • Methods
  • ParameterizedProperty
  • MemberSet
  • Event
  • Dynamic

Conclusion: In the article, we have seen how can we explore or modify any instance object with some very useful PowerShell commands. Now, we also know that what are supported types available for an object based on its members.

Leave a Reply

Up ↑

%d bloggers like this: