使用ForEach和Get-ChildItem -recurse

时间:2012-07-19 19:49:43

标签: powershell

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

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

foreach ($row in $table)
{
  $row[0]
  $row[1]
}

如果我尝试按原样输出$table,它看起来很完美,所有文件都有两列数据。如果我尝试使用foreach(如上所述),我会收到"Unable to index into an object of type Microsoft.PowerShell.Commands.Internal.Format.FormatEndData."错误消息。

我做错了什么?

3 个答案:

答案 0 :(得分:16)

我不知道为什么你要尝试逐步完成格式化数据。但实际上,$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
}

答案 1 :(得分:11)

在完成数据处理之前,切勿使用任何格式命令。格式命令将所有内容转换为字符串,因此您将丢失原始对象。

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

答案 2 :(得分:0)

我刚才刚刚整理了一些配置文件,并在我的过程中找到了这篇文章,并认为我会分享我如何遍历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 
}
相关问题