简体   繁体   English

使用Powershell递归output文件夹内容分离.txt文件

[英]Using Powershell to recursively output folder contents to separate .txt files

I'm attempting to use Powershell to output my folder contents to a text file recursively, sorted by LastWriteTime.我正在尝试使用 Powershell 到 output 我的文件夹内容递归到文本文件,按 LastWriteTime 排序。

My directory structure looks like this:我的目录结构如下所示:

ProjectData
  Proj1
    file1.txt
    file2.txt
  Proj2
    image1.jpg
    file1.txt

I'm attempting to get an output that looks like this:我正在尝试获取如下所示的 output:

Proj1.txt (contents of txt file to include file1.txt, file2.txt)
Proj2.txt (contents of txt file to include image1.jpg, file1.txt)

I've tried the following, which outputs the entire directory listing into a single txt file.我试过以下方法,它将整个目录列表输出到一个 txt 文件中。 I'm not sure it's possible to do what I want with Powershell.我不确定是否可以用 Powershell 做我想做的事。

Get-ChildItem 'C:\Users\hmd\Desktop\PSTest' | Sort-Object LastWriteTime >> 'C:\Users\hmd\Desktop\PSTest\output.txt'

As well, this produces similar results:同样,这会产生类似的结果:

Get-ChildItem -Recurse C:\Users\hmd\Desktop\PSTest | ForEach-Object { $_.Name } > C:\Users\hmd\PSTest\output.txt

I think what needs to happen is, in the ForEach loop, it needs to recursively look into each directly and output the txt file.我认为需要发生的是,在 ForEach 循环中,它需要递归地直接查看每个和 output txt 文件。 I'm unclear on how to approach this and would appreciate any suggestions/tips.我不清楚如何处理这个问题,如果有任何建议/提示,我将不胜感激。

If I'm understanding correctly you need to first look for all folders 1 level deep then get all files for each folder:如果我理解正确,您需要先查找 1 层深的所有文件夹,然后获取每个文件夹的所有文件:

# look for all directories 1 level deep
Get-ChildItem ProjectData -Directory | ForEach-Object {
    # construct the destination path for this folder
    $dest = Join-Path 'C:\Users\hmd\Desktop\PSTest' -ChildPath "$($_.Name).txt"
    # get all files `Name` from this directory (recursively)
    ($_ | Get-ChildItem -Recurse -File | Sort-Object LastWriteTime).Name |
        # store the files in a txt file using the parent folder name
        Set-Content $dest
}

If you want all files in a single line joined by a delimiter you can use -join :如果您希望一行中的所有文件都由定界符连接,您可以使用-join

($_ | Get-ChildItem -Recurse -File | Sort-Object LastWriteTime).Name -join ','

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM