[英]Output multiple .csv files appending the .csv file name as the source folder name with powershell
I have 30 folders.我有 30 个文件夹。 Each folder contains 22 .text files.每个文件夹包含 22 个 .text 文件。 I am trying to get the filenames and row count of each .text files and output it in a .csv file, appending the name of the .csv file with the name of each subfolder.我正在尝试获取每个 .text 文件的文件名和行数,并将其输出到 .csv 文件中,将 .csv 文件的名称附加到每个子文件夹的名称。
The script I made works but it will pull all the .text files from all subfolders and output it in a single .csv file.我制作的脚本有效,但它会从所有子文件夹中提取所有 .text 文件并将其输出到单个 .csv 文件中。
Any idea how I can create one .csv file per subfolder ?知道如何为每个子文件夹创建一个 .csv 文件吗?
$results = Get-ChildItem "C:\Users\testserver\Documents\logfiles\*.txt" -Recurse | % { $_ | select name, @{n="lines";e={get-content $_ | measure-object -line | select -expa lines } } } | Select-Object name, lines
$results | Export-Csv "C:\Users\testserver\Documents\results.csv" -notype
Use the Group-Object
cmdlet to process the files grouped by the directory they reside in:使用Group-Object
cmdlet 处理按文件所在目录分组的文件:
$inDir = 'C:\Users\testserver\Documents\logfiles'
$outDir = 'C:\Users\testserver\Documents'
Get-ChildItem -File -Recurse -Filter *.txt $inDir |
Group-Object DirectoryName |
ForEach-Object {
$outFile = Join-Path $outDir "results-$(Split-Path -Leaf $_.Name).csv"
$_.Group |
Select-Object Name, @{ n="Lines"; e={ (Get-Content $_.FullName | Measure-Object -Line).lines } } |
Export-Csv -NoTypeInformation $outFile
}
The above creates output files such as results-foo.csv
in $outDir
, where foo
is the name of a subdirectory containing *.txt
files.以上在$outDir
创建了诸如results-foo.csv
输出文件,其中foo
是包含*.txt
文件的子目录的名称。
Note that the assumption is that no two subdirectories in the target $inDir
directory tree have the same name;请注意,假设目标$inDir
目录树中没有两个子目录具有相同的名称; more work is needed if you need to handle such collisions, such as reflecting the relative paths in the file name, with \\
replaced with a substitute char.如果您需要处理此类冲突,则需要做更多工作,例如反映文件名中的相对路径,将\\
替换为替代字符。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.