In Powershell, what is the difference between -Property and -ExpandProperty?

Running the cmdlets, the outputs are slightly different, and I'm just trying to understand the difference between the two cmdlets and why you would use one over the other.

Example:

Get-Date | Select -Property DayOfWeek 

Output:

DayOfWeek --------- Saturday 


Get-Date | Select -ExpandProperty DayOfWeek Saturday 
1

1 Answer

Intro

You can inspect any object in Powershell by feeding it to Format-List cmdlet:

PS> Get-Date | Format-List DisplayHint : DateTime Date : 2018-10-21 0:00:00 Day : 21 DayOfWeek : Sunday DayOfYear : 294 Hour : 18 Kind : Local Millisecond : 28 Minute : 38 Month : 10 Second : 36 Ticks : 636757439160281486 TimeOfDay : 18:38:36.0281486 Year : 2018 DateTime : 21 жовтня 2018 р. 18:38:36 

Then, you can change the object, eg. create the new object with subset of properties of original object. You do this using Select-Object cmdlet and with the list of required properties in -Property parameter.

Select-Object has default alias Select, but I suggest that while learning Powershell and exchanging your code with external parties, eg. Superuser.com you do not use aliases, but only full names of cmdlets for the sake of clarity

Answer

  • Get-Date | Select-Object -Property DayOfWeek will create object which has only one property DayOfWeek of the object returned by Get-Date

  • Get-Date | Select-Object -ExpandProperty DayOfWeek will return the String with the content of DayOfWeek property

3

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like