简体   繁体   中英

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

$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.

The Problem with your code is that you are collection all the content of all Files in your $lines-Variable . And there is no Information about the underlying File(-names) any more. 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 ! To reference the file name without the extension (ie. a from a.txt ), reference the BaseName property:

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.

$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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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