为什么圆括号会更改迭代类型


PS > Get-Item env: | Select-Object -First 1 | ForEach-Object GetType
IsPublic IsSerial Name                                     BaseType
-------- -------- ----                                     --------
False    True     ValueCollection                          System.Object
PS > (Get-Item env:) | Select-Object -First 1 | ForEach-Object GetType
IsPublic IsSerial Name                                     BaseType
-------- -------- ----                                     --------
True     True     DictionaryEntry                          System.ValueType

序言:我想知道为什么我不能使用Where Object来过滤Get-Item env:

p.S.以防万一,过滤env:的解决方案

  1. (Get-Item env:) | Where-Object Name -eq 'PUBLIC'
  2. Get-Item env:* | Where-Object Name -eq 'PUBLIC'
  3. Get-ChildItem env: | Where-Object Name -eq 'PUBLIC'
  4. gi env: |% GetEnumerator |? Name -eq 'PUBLIC'(添加在@santisq回答后,他删除了它)

然而,尽管Get-Item env:列出了所有env变量(但文档中说,当*未设置为指向时,不应该列出),但您无法筛选Get-Item env: | Where-Object Name -eq 'PUBLIC,因为Get-Item env: | Measure-Object计数为1

环境:PSV版本5.1.9041.610

EnvC一样是PsDrive,但具有不同的提供程序(Environment提供程序)。

默认情况下,Get-Item只返回项目本身,而不返回项目内容。它具有返回项目内容的功能。使用分组运算符()强制枚举,并在通过管道发送任何内容之前运行内部命令直至完成。

Get-Item env:返回一个未计数的集合,这就是计数为1的原因。(Get-Item env:)枚举内部集合,这就是计数大于1的原因。如果你想要PsDrive中包含的项目,你应该只使用Get-ChildItem env:。在路径后面添加*会指示命令返回由*匹配的每个单独的子项,这与没有尾随*Get-ChildItem相同只有在枚举集合时,才能对包含的项应用筛选逻辑

# No enumeration
Get-Item -Path env: | Measure | Select -Expand Count
1
Get-Item -Path env: | Where Name -eq 'PUBLIC' # returns nothing
# Forced enumeration
(Get-Item -Path env:) | Measure | Select -Expand Count
44
(Get-Item -Path env:) | Where Name -eq 'PUBLIC'
Name                           Value
----                           -----
PUBLIC                         C:UsersPublic
# Implied enumeration by returning targeting child items
Get-Item -Path env:* | Measure | Select -Expand Count
44
# returns child items of target
Get-ChildItem -Path env: | Measure | Select -Expand Count
44

最新更新