使用ForEach和Get-ChildItem -recurse

11 powershell

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

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

foreach ($row in $table)
{
  $row[0]
  $row[1]
}
Run Code Online (Sandbox Code Playgroud)

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

我究竟做错了什么?

Chr*_*s N 18

我不知道你为什么要尝试逐步完成格式化数据.但实际上,$table它只是一个字符串集合.所以你可以做到以下几点:

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

foreach ($row in $table)
{
  $row
}
Run Code Online (Sandbox Code Playgroud)

但我不知道你为什么要这样做.如果您尝试对文件中的数据执行某些操作,可以尝试以下操作:

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


EBG*_*een 11

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

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

  • 对于它的价值,这个问题已经足够了,我确信在那里有一个重复的问题.我没有迅速看到一个.如果有人遇到它,发帖,我会得到关闭的投票开始. (2认同)