如何提取邮件文件接收日期并转换为yyyy_mm_dd_hh_mm格式?
Got it, here's the complete PowerShell script to extract the received date from your EML file's 4th line, convert it to your desired format, and append it to the filename:
# Navigate to the directory containing your EML file cd C:\Temp\Test # Define the target EML file (adjust this if you're processing multiple files later) $emailFilePath = "RemoteBackupServer.eml" # Pull the 4th line (index 3) which holds the raw date string $rawDateString = Get-Content $emailFilePath | Select-Object -Index 3 # Parse the raw date string into a proper DateTime object # The format string matches your input: "Tue, 1 May 2018 15:56:12 +0200" $parsedDate = [DateTime]::ParseExact( $rawDateString, "ddd, d MMM yyyy HH:mm:ss zzz", [System.Globalization.CultureInfo]::InvariantCulture ) # Format the DateTime object to your required yyyy_mm_dd_hh_mm pattern $formattedDate = $parsedDate.ToString("yyyy_MM_dd_HH_mm") # Generate the new filename (original name + formatted date + original extension) $originalFileName = [System.IO.Path]::GetFileNameWithoutExtension($emailFilePath) $fileExtension = [System.IO.Path]::GetExtension($emailFilePath) $newFileName = "$originalFileName`_$formattedDate$fileExtension" # Rename the file Rename-Item -Path $emailFilePath -NewName $newFileName
Key Details Explained:
Parsing the Date: The
ParseExactmethod is critical here because it lets us explicitly match the exact format of your date string. The format tokens break down like this:ddd: Abbreviated weekday (e.g., "Tue")d: Day of the month without leading zero (e.g., "1")MMM: Abbreviated month name (e.g., "May")yyyy: 4-digit yearHH: 24-hour format hour (e.g., "15")mm: Minutesss: Secondszzz: Time zone offset (e.g., "+0200")- Using
InvariantCultureensures the parsing works regardless of your system's regional settings.
Generating the Filename: Using
[System.IO.Path]methods to split the filename and extension is safer than manual string splitting—it handles edge cases like filenames with multiple dots automatically.
Bonus: Batch Processing Multiple EML Files
If you need to do this for all EML files in the directory, use this loop instead:
cd C:\Temp\Test Get-ChildItem -Filter *.eml | ForEach-Object { $rawDateString = Get-Content $_.FullName | Select-Object -Index 3 $parsedDate = [DateTime]::ParseExact( $rawDateString, "ddd, d MMM yyyy HH:mm:ss zzz", [System.Globalization.CultureInfo]::InvariantCulture ) $formattedDate = $parsedDate.ToString("yyyy_MM_dd_HH_mm") $newFileName = "$($_.BaseName)`_$formattedDate$($_.Extension)" Rename-Item -Path $_.FullName -NewName $newFileName }
Just make sure all your EML files have the date on the 4th line—if some vary, you might need to adjust the logic to search for the Received: header instead of relying on line index!
内容的提问来源于stack exchange,提问作者Skanderbeg

