Tips and Tricks

How to get value for a property from a object in Powershell Variable ?


PowerShell is a very unique and powerful language. Objects are the main reason behind it. It’s default use of object makes it different then any other shell or scripting language.

Objects are everywhere in PowerShell. I will not waste any more time with some random information here so lets get back to our original question.

Lets take an example ! I want to fetch object id of AD group

PS> Get-AzADGroup -DisplayName "my-group" | Select Idoutput will be like -

However, this use of the Select-Object cmdlet (built-in alias is select) is not much of use here as this still returns a object that requires you to access its property again !

We can use Select-Object to extract a single property value, via 
-ExpandProperty <PropertyName> parameter:
PS> Get-AzADGroup -DisplayName "developers" | Select
-ExpandProperty Id


How we reach to this ?

To discover information about an object (members) in powershell, you can use the Get-Member cmdlet.
Consider this you want to view members for a particular object returned via the Get-AzADGroup cmdlet.

PS> Get-AzADGroup -DisplayName "developers" | Get-MemberTypeName: Microsoft.Azure.Commands.ActiveDirectory.PSADGroupName            MemberType Definition
---- ---------- ----------
Equals Method bool Equals(System.Object obj)
GetHashCode Method int GetHashCode()
GetType Method type GetType()
ToString Method string ToString()
Description Property string Description {get;set;}
DisplayName Property string DisplayName {get;set;}
Id Property string Id {get;set;}
MailNickname Property string MailNickname {get;set;}
ObjectType Property string ObjectType {get;}
SecurityEnabled Property System.Nullable[bool] SecurityEnabled {get;set;}
Type Property string Type {get;set;}

You can use another way to do this as well.

PS> $ObjId = (Get-AzADGroup -DisplayName "developers").Id
PS> Write-Host $ObjId

Thanks !

In quest of understanding How Systems Work !

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store