【问题标题】:Using ForEach with Get-ChildItem -recurse将 ForEach 与 Get-ChildItem -recurse 一起使用
【发布时间】:2012-07-19 19:49:42
【问题描述】:

我正在尝试获取特定子文件夹结构中文件的递归列表,然后将它们保存到表中,以便我可以使用 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." 错误消息。

我做错了什么?

【问题讨论】:

    标签: powershell


    【解决方案1】:

    我完全不知道您为什么要逐步检查格式化数据。但事实上,$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 表。你的第二个例子让我得到了我所需要的。谢谢!
    【解决方案2】:

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

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

    【讨论】:

    • 对于它的价值,这个问题足够多,我敢肯定在某个地方有一个欺骗问题。我没有很快看到一个。如果有人遇到它,请发帖,我会开始投票。
    【解决方案3】:

    我刚才正在清理一些配置文件,并在我的过程中发现了这篇文章,并想我会分享我如何循环遍历 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 
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-02-21
      • 1970-01-01
      • 2014-01-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-11-06
      相关资源
      最近更新 更多