从powershell,ls -R *.txt
将按目录递归列出文件,或者甚至更好:
PS> Get-ChildItem -Path C:\Test -Name
日志
anotherfile.txt
Command.txt
CreateTestFile.ps1
ReadOnlyFile.txt
但是如何将其输入数组呢?我想要一个文件(?)对象本身的数组,看看:
Get-ChildItem "C:\WINDOWS\System32" *.txt -Recurse | Select-Object FullName
https://stackoverflow.com/a/24468733/262852
我正在寻找一系列带有PowerShell的“文件”对象来自这些类型的命令。
可能更好的语法:
Copy-Item -Filter *.txt -Path c:\data -Recurse -Destination C:\temp\text
但不是复制项目,我只想要一个对象,或者更确切地说是对象数组。不是文件的路径,而不是文件的路径,但可能是PowerShell引用或指向文件的指针。
(现在阅读fine手册。)
Get-ChildItem "C:\test" -Recurse
将在数组中返回FileInfo和DirectoryInfo对象的数组
我们可以在这里看到一个示例
Get-ChildItem "C:\test" -Recurse | %{
$_.gettype()
}
返回
IsPublic IsSerial Name BaseType
-------- -------- ---- --------
True True DirectoryInfo System.IO.FileSystemInfo
True True DirectoryInfo System.IO.FileSystemInfo
True True FileInfo System.IO.FileSystemInfo
True True DirectoryInfo System.IO.FileSystemInfo
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
部分,online help也是如此,但在Get-ChildItem
的情况下,它不那么具体,因为Get-ChildItem
也适用于文件系统以外的提供者。$var = ...
)中捕获输出时,以下逻辑适用:
如果输出两个或多个对象,则会将它们收集在常规PowerShell数组中,该数组的类型为[object[]]
(即使实际元素具有特定类型)。
如果输出一个对象,则按原样输出;也就是说,它没有包装在一个数组中。
如果没有输出对象,则输出“数组值null”,[System.Management.Automation.Internal.AutomationNull]::Value
,在大多数情况下,它的行为类似于$null
,并且没有可见的输出 - 有关详细信息,请参阅this answer。因此,当在变量中捕获时,给定命令可以在情境上返回:
[System.Management.Automation.Internal.AutomationNull]::Value
)要确保将给定命令的输出始终视为数组,您有两个选择:
@(...)
,array subexpression operator;例如
$fileSystemObjects = @(Get-ChildItem -Recurse -Filter *.txt)
[array]
对类型约束目标变量(与[object[]]
相当,并且比[array] $fileSystemObjects = Get-ChildItem -Recurse -Filter *.txt
更容易输入)。
.Count
也就是说,在PSv3 +中,你经常不必担心给定变量是否包含标量(单值)或数组,因为标量可以隐式地被视为数组:你甚至可以在标量上调用[0]
,并使用索引([-1]
,this answer) ) - 有关详细信息,请参阅qazxswpoi。