How can I rename multiple files in a folder to include :
- MM_YYYY
- File 1 in XX
- Number of lines in the file
Example :
Current file name :
- SRA_0400041325.TXT
- SRA_0400027561.TXT
- SRA_0400013497.TXT
After :
- SRA_0400041325_03_2022_1-3_720.TXT
- SRA_0400027561_03_2022_2-3_433.TXT
- SRA_0400013497_03_2022_3-3_1720.TXT
How to do that in PowerShell ?
Thanks.
EDIT 1 :
I've tried this :
$Month = (Get-Date).ToString("MM")
$Year = (Get-Date).ToString("yyyy")
$MonthYear = $Month "-" $Year
$NumberOfFiles = (Get-ChildItem | Measure-Object).Count
$NumberOfLines = Get-Content SRA_0400041325.TXT | Measure-Object -line | Select-Object -ExpandProperty Lines
$PartToAdd = $MonthYear "_" $NumberOfFiles "_" $NumberOfLines
Write-Host $PartToAdd
But I don't know how to include a ForEach
CodePudding user response:
As you've found, you can use Get-ChildItem
to discover the files and Get-Content
to enumerate the contents and count the lines.
Now you just need a variable to keep track of which number file you're currently processing:
# Prepare the date parts
$Month = (Get-Date).ToString("MM")
$Year = (Get-Date).ToString("yyyy")
# Discover the files
$Files = @(Get-ChildItem -File)
$NumberOfFiles = $Files.Count
# We'll use this to keep track of which number file we're operating on
$FileCounter = 1
foreach($file in $files){
$NumberOfLines = ($file |Get-Content |Measure-Object -Line).Lines
# Construct the file-count part
$FileCountString = $FileCounter,$NumberOfFiles -join '-'
# Remember to update the file counter
$FileCounter
# Construct the new file name
$newName = $file.BaseName,$Month,$Year,$FileCountString,$NumberOfLines -join '_'
# Rename the file
$file |Rename-Item -NewName $newName
}