[英]Passing filename to variable in Powershell?
I have hundreds of file in working directory that needs to be processed.我在工作目录中有数百个文件需要处理。 It looks similar to this
它看起来与此相似
a.txt
b.txt
c.txt
d.txt
All of these file can be processed manually like this所有这些文件都可以像这样手动处理
$lines = Get-Content "a.txt"
foreach ($line in $lines){
Out-File -FilePath "a-done.txt" -Encoding UTF8 -Append -InputObject ($line.Split(","))[0]
}
How to automate this process using loop by passing all filename to variable above.如何通过将所有文件名传递给上面的变量来使用循环自动化这个过程。
I have tried foreach loop but it's not working我已经尝试过 foreach 循环,但它不起作用
$lines = Get-Content "path/*.txt"
foreach ($line in $lines){
Out-File -FilePath "$lines-processed.txt" -Encoding UTF8 -Append -InputObject ($line.Split(","))[0]
}
What do I miss here?我在这里想念什么?
Youre looping through the lines of get-content, not where the filenames are saved.您正在遍历获取内容的行,而不是保存文件名的位置。 You need probably an extra step eg
你可能需要一个额外的步骤,例如
$items = Get-ChildItem 'C:\Users\Alex\Desktop\oop'
foreach ($item in $items) {
<#your processin with get-content here#>
echo $item.name
echo "$item-processed.txt"
}
I misunderstodd in the first time.我第一次理解错了。 I hope I am right now:
我希望我现在是:
You want so save one done-File
per one input file.您希望
done-File
文件。
The Problem with your code is that you are collection all the content of all Files in your $lines-Variable
.您的代码的问题是您正在收集
$lines-Variable
中所有文件的所有内容。 And there is no Information about the underlying File(-names)
any more.并且不再有关于底层
File(-names)
的信息。 Instead you have to loop over all the files an handle them seperately.相反,您必须遍历所有文件并单独处理它们。
The solution suggested:解决方案建议:
$files = dir *.txt -Exclude *done.txt
foreach ($f in $files) {
Get-Content $f | % {$_.split(',')[0]} |
Out-File ($f.DirectoryName + '\' + $f.Basename + '-done.txt') -Encoding UTF8}
Regards Martin问候马丁
To discover the files themselves, you'll want to use Get-ChildItem
instead of Get-Content
!要自己发现文件,您需要使用
Get-ChildItem
而不是Get-Content
! To reference the file name without the extension (ie. a
from a.txt
), reference the BaseName
property:要引用不带扩展名的文件名(即
a.txt
中的a
),请引用BaseName
属性:
foreach($file in Get-ChildItem .\path\ -Filter *.txt){
foreach ($line in $file |Get-Content){
Out-File -FilePath "$($file.BaseName)-done.txt" -Encoding UTF8 -Append -InputObject ($line.Split(","))[0]
}
}
Here's an example of how I combine csv files into one big CSV.这是我如何将 csv 文件组合成一个大 CSV 的示例。
$txtFilter = "D:\Temp\*.csv"
$fileOutputSummary = "D:\Temp\Summary.csv"
$list = Get-ChildItem -Path $txtFilter | select FullName
$iItems = $list.Count
$i = 0
ForEach($file in $list){
$i++
Write-Host "Combining ($i of $iItems) `r"
Write-Progress -Activity "Combining CSV files" -PercentComplete ($i / $iItems*100)
Import-Csv -Path $file.FullName | Export-Csv -Path $fileOutputSummary -Append -NoTypeInformation
Sleep 1
} # end ForEach file
I hope my example helps.我希望我的例子有所帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.