【问题标题】:PowerShell - Copy specific lines from multiple specific nested filesPowerShell - 从多个特定嵌套文件中复制特定行
【发布时间】:2017-06-06 21:03:33
【问题描述】:

因此,文件夹结构如下所示:

根文件夹

  • 根文件夹
    • 子文件夹 1
      • 子子文件夹 1
        • totals.txt
      • 子子文件夹2
        • totals.txt
    • 子文件夹 2
      • 子子文件夹 1
        • totals.txt
      • 子子文件夹2
        • totals.txt

我想要做的是递归遍历totals.txt 文件的这些子文件夹。读取内容,并将第 22、26、30、34、38 和 42 行(第一行为 0 而不是 1)复制到单个组合文件中。

我从这段代码开始:

Get-ChildItem -Recurse | Where-Object {$_ -like "totals.txt" } | Get-Content | Select-Object -Index 22,26,30,34,38,42  | Add-Content "DataInportFile.txt"

但是这只会找到 RootFolder\SubFolder\SubSubFolder\totals.txt 然后退出脚本。不是我要找的...

我需要的是上面的脚本继续递归搜索下一个文件,直到所有目录都在结构中搜索完毕。所以我用了这个:

Get-ChildItem -Recurse | ForEach-Object {$_ -like "totals.txt" } | Get-Content | Select-Object -Index 22,26,30,34,38,42  | Add-Content "DataInportFile.txt"

但是,这个脚本出错了

C:\Users\user1\scripts\Untitled1.ps1:1 char:69
+ ... urse | ForEach-Object {$_ -like "totals.txt" } | $_.filename #| Get- ...
+                                                       ~~~~~~~~~~~
Expressions are only allowed as the first element of a pipeline.
    + CategoryInfo          : ParserError: (:) [], ParentContainsErrorRecordException
    + FullyQualifiedErrorId : ExpressionsMustBeFirstInPipeline

我可以使用一些帮助来弄清楚这个 powershell 脚本的其余部分。如此接近,但没有快乐。感谢您的帮助。

【问题讨论】:

    标签: powershell


    【解决方案1】:

    意识到我需要遍历数组

    供其他人参考,此代码按要求工作:

    Get-ChildItem -Recurse | Where-Object {$_ -like "totals.txt" } | 
        %{
            (Get-Content $_.FullName) | Select-Object -Index 22,26,30,34,38,42  | Add-Content "DataInportFile.txt"
            }
    

    【讨论】:

    • Get-ChildItem -Recurse -Filter "totals.txt" | 没有 where 效率更高。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-04-10
    • 2013-01-27
    • 2021-11-01
    • 2019-06-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多