windows - 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.)
解决方案
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
,并导致没有可见输出 - 有关详细信息,请参阅此答案。
- 如果输出两个或更多对象,它们将被收集在一个常规的 PowerShell 数组中,该数组是类型
因此,当在变量中捕获时,给定的命令可能会根据情况返回:
- 对象数组
- 单个对象
- “无” (
[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]
) - 请参阅这个答案的详细信息。
推荐阅读
- node.js - vscode“去定义”可以在node_modules中显示实际的js代码而不是打字稿版本吗?
- android - 从 Flutter 的方法通道访问 Kotlin 中的参数数据
- kubernetes - kubeadmin 用户可以创建超过 ClusterResourceQuota 硬限制的资源吗?
- tensorflow - TensorFlow:整个训练过程中的 CosineDifference ObjFunc 常量
- reactjs - 固定表布局与更新的值不匹配 - reactjs
- c - 如何在c中解析tcp数据包有效负载
- excel - 遍历范围的VBA搜索
- angular - 错误:BrowserModule 已加载
- swift - 如何编写一些正则表达式来查找子域并在 Swift 中替换值
- html - 文章网格没有一直延伸到边缘