GetType used in PowerShell, difference between variables

PowershellPowershell 2.0

Powershell Problem Overview


What is the difference between variables $a and $b?

$a = (Get-Date).DayOfWeek
$b = Get-Date | Select-Object DayOfWeek

I tried to check

$a.GetType
$b.GetType

MemberType          : Method
OverloadDefinitions : {type GetType()}
TypeNameOfValue     : System.Management.Automation.PSMethod
Value               : type GetType()
Name                : GetType
IsInstance          : True

MemberType          : Method
OverloadDefinitions : {type GetType()}
TypeNameOfValue     : System.Management.Automation.PSMethod
Value               : type GetType()
Name                : GetType
IsInstance          : True

But there seems to be no difference although the output of these variables looks different.

Powershell Solutions


Solution 1 - Powershell

First of all, you lack parentheses to call GetType. What you see is the MethodInfo describing the GetType method on [DayOfWeek]. To actually call GetType, you should do:

$a.GetType();
$b.GetType();

You should see that $a is a [DayOfWeek], and $b is a custom object generated by the Select-Object cmdlet to capture only the DayOfWeek property of a data object. Hence, it's an object with a DayOfWeek property only:

C:\> $b.DayOfWeek -eq $a
True

Solution 2 - Powershell

Select-Object creates a new psobject and copies the properties you requested to it. You can verify this with GetType():

PS > $a.GetType().fullname
System.DayOfWeek

PS > $b.GetType().fullname
System.Management.Automation.PSCustomObject

Solution 3 - Powershell

Select-Object returns a custom PSObject with just the properties specified. Even with a single property, you don't get the ACTUAL variable; it is wrapped inside the PSObject.

Instead, do:

Get-Date | Select-Object -ExpandProperty DayOfWeek

That will get you the same result as:

(Get-Date).DayOfWeek

The difference is that if Get-Date returns multiple objects, the pipeline way works better than the parenthetical way as (Get-ChildItem), for example, is an array of items. This has changed in PowerShell v3 and (Get-ChildItem).FullPath works as expected and returns an array of just the full paths.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionjraraView Question on Stackoverflow
Solution 1 - PowershellCédric RupView Answer on Stackoverflow
Solution 2 - PowershellShay LevyView Answer on Stackoverflow
Solution 3 - PowershellMasterCheffinatorView Answer on Stackoverflow