首页 > 解决方案 > return array of objects from Get-ChildItem -Path

问题描述

From powershell, ls -R *.txt will list files recursively by directory, or, even better:

PS> Get-ChildItem -Path C:\Test -Name

logs

anotherfile.txt
Command.txt
CreateTestFile.ps1
ReadOnlyFile.txt

but how do I feed this into an array? I would like an array of the file (?) object itself, looking at:

Get-ChildItem "C:\WINDOWS\System32" *.txt -Recurse | Select-Object FullName

https://stackoverflow.com/a/24468733/262852

I'm looking for an array of "file" objects with powershell from these types of commands.

probably better syntax:

Copy-Item -Filter *.txt -Path c:\data -Recurse -Destination C:\temp\text

but rather than copy the items, I just want an object, or rather, array of objects. Not the path to a file, not the file, but, presumably, a powershell reference or pointer to a file.

(Reading the fine manual now.)

标签: windowspowershellfiledirectorysysadmin

解决方案


tl;博士

  • 当您在变量(例如 )中捕获 PowerShell 语句的输出时,如果有两个或更多输出对象
    $output = Get-ChildItem ...,它会自动收集到一个数组中。

  • 为了确保始终使用数组——即使只有一个没有输出对象——使用@(...)(例如,
    $output = @(Get-ChildItem ...)


  • PowerShell cmdlet,例如Get-ChildItem,可以输出任意数量的对象。

    • Get-ChildItem输出[System.IO.FileInfo]和/或[System.IO.DirectoryInfo]对象,取决于是否正在输出有关文件和/或目录的信息。

    • 确定给定 cmdlet 的输出对象类型

      • 运行,例如,(Get-Command Get-ChildItem).OutputType
      • 如果这不起作用,或者要查看特定调用的输出类型,请使用
        Get-ChildItem | Get-Member.
      • Get-Help -Full Get-ChildItem也应该显示一个OUTPUTS部分,在线帮助也是如此,尽管在Get-ChildItem它不太具体的情况下并不是这样,因为它Get-ChildItem也适用于文件系统以外的提供者。
  • 输出到管道时,每个输出对象都被单独传递给管道中的下一个命令,通常是立即处理。

  • 当在变量( )中捕获输出$var = ...时,适用以下逻辑:

    • 如果输出两个或更多对象,它们将被收集在一个常规的 PowerShell 数组中,该数组是类型[object[]](即使实际元素具有特定类型)。
    • 如果输出一个对象,则按原样输出;也就是说,它没有包装在数组中。
    • 如果没有输出任何对象,则输出“数组值 null” [System.Management.Automation.Internal.AutomationNull]::Value,在大多数情况下其行为类似于$null,并导致没有可见输出 - 有关详细信息,请参阅此答案

因此,当在变量中捕获时,给定的命令可能会根据情况返回

  • 对象数组
  • 单个对象
  • “无” ( [System.Management.Automation.Internal.AutomationNull]::Value)

为确保给定命令的输出始终被视为数组,您有两种选择:

  • 使用@(...)数组子表达式运算符;例如

    • $fileSystemObjects = @(Get-ChildItem -Recurse -Filter *.txt)
  • [array]使用(等同于,并且比 更容易键入)对目标变量进行类型约束[object[]]

    • [array] $fileSystemObjects = Get-ChildItem -Recurse -Filter *.txt

也就是说,在 PSv3+ 中,您通常不必担心给定变量是否包含标量(单个值)或数组,因为标量可以隐含地被视为数组:您.Count甚至可以在标量上调用,并使用索引 ( [0], [-1]) - 请参阅这个答案的详细信息。


推荐阅读