Tuesday, January 2, 2018

Objects, properties and methods in PowerShell

An object is something which has a set of properties that describes it and set of methods which are the actions you can perform on it. Lets look into an example.

Get the virtual machines from a Hyper-V host: Get-VM


The result shown in the above screenshot is not just text. These are objects and associated parameters. There are 4 virtual machine objects and its associated properties like Name, State, Uptime etc. The output shows only limited properties but there are more number of properties associated with a virtual machine object.

You can find all the properties and methods available for an object using: Get-Member

Example: Get-VM | Get-Member


Here you can see all the properties and methods available. 

Property

You can select the properties as per requirement.

Get-VM | select -Property Name, IsClustered, MemoryDemand, ProcessorCount, NumaAligned, Generation, Path


To retrieve properties of a specific virtual machine object, use the below:

Get-VM -name AD | select -Property Name, IsClustered, MemoryDemand, ProcessorCount, NumaAligned, Generation, Path


You can assign this to a string variable as shown below:

$vm = Get-VM -name AD | select -Property Name, IsClustered, MemoryDemand, ProcessorCount, NumaAligned, Generation, Path

And the individual properties of that object can be retrieved too!


Method

Example: Get-Service -Name bits

To get all the properties and methods for this object: Get-Service -Name bits | gm

Note: 'gm' is alias for Get-Member


In the above screenshot you can see several methods like start, stop, refresh etc. These are actions that can be performed on the service controller object "Bits".

Below screenshot shows how to start and stop "bits" service using Start and Stop methods.

To start bits service: (Get-Service -Name bits).Start()
To stop bits service: (Get-Service -Name bits).Stop()


Hope it was useful to you. Cheers!

No comments:

Post a Comment