本文介绍了PowerShell中使用的GetType,变量之间的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

变量$a$b 有什么区别?

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

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

我试图检查

$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.

推荐答案

首先,您缺少调用 GetType 的括号.您看到的是描述 [DayOfWeek] 上的 GetType 方法的 MethodInfo.要实际调用 GetType,您应该这样做:

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();

您应该看到 $a 是一个 [DayOfWeek],而 $b 是由 Select-Object cmdlet 仅捕获数据对象的 DayOfWeek 属性.因此,它是一个只有 DayOfWeek 属性的对象:

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

这篇关于PowerShell中使用的GetType,变量之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-16 15:12