arrays - 将两个不同的Get-ChildItem调用的结果合并为一个变量,以对它们进行相同的处理

标签 arrays powershell get-childitem

我正在尝试编写PowerShell脚本以从多个目录构建文件列表。将所有目录添加到主列表后,我想对所有文件进行相同的处理。

这就是我所拥有的:

$items = New-Object Collections.Generic.List[IO.FileInfo]

$loc1 = @(Get-ChildItem -Path "\\server\C$\Program Files (x86)\Data1\" -Recurse)
$loc2 = @(Get-ChildItem -Path "\\server\C$\Web\DataStorage\" -Recurse)

$items.Add($loc1) # This line fails (the next also fails)
$items.Add($loc2)

# Processing code is here

失败并显示此错误:

Cannot convert argument "0", with value: "System.Object[]", for "Add" to type "System.IO.FileInfo": "Cannot convert the "System.Object[]" va lue of type "System.Object[]" to type "System.IO.FileInfo"."



我对这种情况的正确方法最感兴趣。我意识到我的代码是一种非常C的实现方式-如果有更多的PowerShell方法来完成同一任务,我将全力以赴。关键是$loc#'s的数量可能会随时间变化,因此在生成的代码中添加和删除一两个应该很容易。

最佳答案

不确定您是否需要此处的通用列表。您可以只使用PowerShell数组,例如:

$items  = @(Get-ChildItem '\\server\C$\Program Files (x86)\Data1\' -r)
$items += @(Get-ChildItem '\\server\C$\Web\DataStorage\' -r)

可以使用+=连接PowerShell数组。

关于arrays - 将两个不同的Get-ChildItem调用的结果合并为一个变量,以对它们进行相同的处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4749979/

相关文章:

windows - 获取与添加/删除程序列表匹配的已安装应用程序列表

powershell - 从 CSV 中删除一行

powershell - 使用 csv 文件中的新名称重命名目录中的文件

php - 将字符串分解为多个单词

php - Laravel 计数多维数组中键值为真的数量

c - 如何在C中逐行读取文件?

iis - 启动/停止iis和mssql的powershell脚本代码

powershell - 为什么Test-Connection强制枚举重解析点?

Powershell 飞溅 : pass ErrorAction = Ignore in hash table

php - 获取数组的第一个元素