Home > other >  Get all files named month by month
Get all files named month by month

Time:11-22

i have system of log that write logs each day with this format: "stat.dat_20220901_235900.txt","stat.dat_20220902_235900.txt",... i need to get content of all files by month and create file named like "September" with all content of daily.

$Date= -Format("MMddyyyy_hhmmss")
$path="C:\Users\**\**\**\**\stat.dat_$Date"
$CharArray =Get-Content -Path $path

CodePudding user response:

This will create the variable $txtArray which will contain the content of all files matching the month 09:

$dateString = Get-Date -Month 09 -UFormat '%Y%m'
$txtArray = Get-ChildItem -Filter "stat.dat_*.txt" -Path "C:\Users\**\**\**\**\" | `
Where-Object {$_.Name -match $("stat\.dat_"   $dateString)} | Get-Content 

CodePudding user response:

Assuming all files in that path are from year 2022, you can do something like this:

$path = 'C:\Users\somewhere'  # the path where the daily files are

Get-ChildItem -Path $path -Filter "stat.dat_*.txt" -File |
Where-Object {$_.BaseName -match '_\d{8}_\d{6}$' } |         # filter more fine-tuned
Group-Object {$_.BaseName -replace '.*_(\d{8})_.*', '$1'} |  # group on just the date part
ForEach-Object {
    # parse out the month number, convert that to the month name and use for the new file name
    $monthNumber = [datetime]::ParseExact($_.Name,'yyyyMMdd', $null).Month
    $monthName   = (Get-Culture).DateTimeFormat.GetMonthName($monthNumber)
    $monthFile   = Join-Path -Path $path -ChildPath ('{0}.txt' -f $monthName)
    # sort the files, get their content and write to the new file
    $_.Group | Sort-Object LastWriteTime | Get-Content | Add-Content -Path $monthFile
}
  • Related