使用ForEach和Get-ChildItem -recurse

21

我正在尝试获取一个特定子文件夹结构的递归文件列表,然后将它们保存到一张表中,以便我可以使用 foreach 循环来处理每一行。 我有以下代码:

$table = get-childitem -recurse | where {! $_.PSIsContainer} | Format-Table Name, Length

foreach ($row in $table)
{
  $row[0]
  $row[1]
}
如果我尝试直接输出$table,它看起来完美,所有文件都有两列数据。如果我尝试使用foreach来逐步遍历(如上所述),我会收到"无法对类型为Microsoft.PowerShell.Commands.Internal.Format.FormatEndData的对象进行索引。"的错误消息。
我做错了什么?
3个回答

35

我不知道你为什么要逐步遍历格式化数据,但实际上,$table 只是一组字符串。因此,你可以执行以下操作:

$table = get-childitem -recurse | where {! $_.PSIsContainer} | Format-Table Name, Length

foreach ($row in $table)
{
  $row
}

但我不知道为什么你要这样做。如果你想对文件中的数据进行操作,可以尝试这个方法:

$files = get-childitem -recurse | where {! $_.PSIsContainer}
foreach ($file in $files)
{
    $file.Name
    $file.length
}

我想做的是从gci创建一个数据数组,然后使用foreach循环和一系列“INSERT INTO”命令构建一个SQL表。你的第二个示例正好给了我所需的东西。谢谢! - user1491315

16

在完全处理完数据之前,不要使用任何格式命令。格式命令会将所有内容转换为字符串,这样您就会失去原始对象。

$table = get-childitem -recurse | where {! $_.PSIsContainer}
foreach($file in $table){
    $file.Name
    $file.FullName
}

3
就我所知,这种问题经常出现,我相信一定有重复的问题存在。但我没有立刻找到。如果有人找到了,请发布并告诉我,我会开始关闭该问题。 - EBGreen

1

刚才我在整理一些配置文件时,发现了这篇文章,并想分享一下我如何循环遍历get-childitem的结果(ls只是gci的别名吧?)。希望能对某个地方的某个人有所帮助。

$blob = (ls).name 
foreach ($name in $blob) { 
get-childitem "D:\CtxProfiles\$name\Win2012R2v4\UPM_Profile\AppData\Local\Google\Chrome\User Data\Default\Default\Media Cache\f_*" -erroraction 'silentlycontinue'|remove-item -force -recurse -confirm:$false 
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接