将 ForEach 与 Get-ChildItem -recurse 结合使用 [英] Using ForEach with Get-ChildItem -recurse

查看:64
本文介绍了将 ForEach 与 Get-ChildItem -recurse 结合使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

$table = get-childitem -recurse |在哪里 {!$_.PSIsContainer} |格式-表名、长度foreach ($table 中的 $row){$行[0]$行[1]}

如果我尝试按原样输出 $table,它看起来很完美,所有文件都有两列数据.如果我尝试使用 foreach(如上),我会收到 无法索引到 Microsoft.PowerShell.Commands.Internal.Format.FormatEndData 类型的对象." 错误消息.>

我做错了什么?

解决方案

我完全不知道你为什么要单步处理格式化数据.但实际上,$table 只是字符串的集合.因此,您可以执行以下操作:

$table = get-childitem -recurse |在哪里 {!$_.PSIsContainer} |格式-表名、长度foreach ($table 中的 $row){$行}

但我不知道你为什么想要.如果你想对文件中的数据做一些事情,你可以试试这个:

$files = get-childitem -recurse |在哪里 {!$_.PSIsContainer}foreach ($files 中的 $file){$文件名$file.length}

I am trying to get a recursive list of files in a particular subfolder structure, then save them to a table so that I can use a foreach loop to work with each row. I have the following code:

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

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

If I try to output $table as-is, it looks perfect, with two columns of data for all of the files. If I try and step through with foreach (like above), I get the "Unable to index into an object of type Microsoft.PowerShell.Commands.Internal.Format.FormatEndData." error message.

What am I doing wrong?

解决方案

I don't know why you're trying to step through formatted data at all. But as it is, $table is just a collection of strings. So you can do the following:

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

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

But I don't know why you'd want to. If you're trying to do something with the data in the file you could try this:

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

这篇关于将 ForEach 与 Get-ChildItem -recurse 结合使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆