Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Powershell: GetType used in PowerShell, difference between variables

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.

like image 564
jrara Avatar asked Oct 03 '11 11:10

jrara


People also ask

How do you find out what type a variable is in PowerShell?

Use GetType to Get the Data Type of Variable in PowerShell You can use the GetType method to view its data type, as shown below. It displays IsPublic , IsSerial , Name , and BaseType properties of a variable. Output: The Name indicates the data type of a variable.

What PowerShell command is used to compare the difference between the content of two or more?

Compare-Object command in PowerShell is used to compare two objects. Objects can be a variable content, two files, strings, etc. This cmdlet uses few syntaxes to show the difference between objects which is called side indicators. => - Difference in destination object.

Why we use $_ in PowerShell?

$_ is an alias for automatic variable $PSItem (introduced in PowerShell V3. 0; Usage information found here) which represents the current item from the pipe. PowerShell (v6. 0) online documentation for automatic variables is here.


2 Answers

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 
like image 99
Cédric Rup Avatar answered Sep 28 '22 16:09

Cédric Rup


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 
like image 30
Shay Levy Avatar answered Sep 28 '22 17:09

Shay Levy