PowerShell中使用的GetType,变量之间的区别
变量 $a
和 $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
但似乎没有区别,尽管这些变量的输出看起来不同。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
首先,调用 GetType 时缺少括号。您看到的是描述 [DayOfWeek] 上的 GetType 方法的 MethodInfo。要实际调用 GetType,您应该执行以下操作:
您应该看到
$a
是 [DayOfWeek],而$b
是由 Select-Object cmdlet 仅捕获数据对象的 DayOfWeek 属性。因此,它是一个仅具有 DayOfWeek 属性的对象: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:
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:Select-Object 创建一个新的 psobject 并将您请求的属性复制到它。您可以使用 GetType() 验证这一点:
Select-Object creates a new psobject and copies the properties you requested to it. You can verify this with GetType():
Select-Object 返回自定义 PSObject 仅包含指定的属性。即使只有一个属性,您也无法获得 ACTUAL 变量;它被包装在 PSObject 内。
相反,这样做:
这会给你带来相同的结果:
区别在于,如果 Get -Date 返回多个对象,管道方式比括号方式更好,如
(Get-ChildItem)
是一个项目数组。这在 PowerShell v3 和(Get-ChildItem).FullPath
中发生了变化。FullPath 按预期工作并返回仅包含完整路径的数组。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:
That will get you the same result as:
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.