求PowerShell批量转换文件中不一致旧日期格式为ISO 8601/YYYYMMDD的技巧
Got it, let's tackle this batch date conversion problem head-on. Dealing with messy, inconsistent date formats like 10-24-2007, Oct-24-07, or oct-07 is a total pain, but PowerShell has all the tools we need to fix this efficiently. Below is a step-by-step solution that handles all your examples and converts dates to both standard formats.
Step 1: Core Date Conversion Function
First, let's build a reusable function that can parse all the wonky date formats you mentioned and spit out the standardized versions. This uses TryParseExact to safely attempt parsing against multiple format patterns, so it won't break if it hits an unrecognized date.
function Convert-DateToStandardFormats { param( [Parameter(Mandatory=$true)] [string]$InputDate ) # Define all input date formats we need to handle (add more if you have others!) $dateFormats = @( 'MM-dd-yyyy', # Matches 10-24-2007 'MMM-dd-yy', # Matches Oct-24-07 'MMM-yy' # Matches oct-07 (case-insensitive thanks to InvariantCulture) ) $parsedDate = [DateTime]::MinValue # Try parsing with each format; InvariantCulture ensures month abbreviations work regardless of system locale if ([DateTime]::TryParseExact( $InputDate.Trim(), $dateFormats, [System.Globalization.CultureInfo]::InvariantCulture, [System.Globalization.DateTimeStyles]::None, [ref]$parsedDate )) { # Return both desired formats in a hashtable return @{ ISO8601 = $parsedDate.ToString('yyyy-MM-dd') YYYYMMDD = $parsedDate.ToString('yyyyMMdd') } } else { # Warn and return original date if parsing fails (avoids breaking the whole batch) Write-Warning "Skipping unparseable date: '$InputDate'" return @{ ISO8601 = $InputDate YYYYMMDD = $InputDate } } }
Step 2: Batch Process Files
Now let's wrap this function in a script that scans through your files, finds all matching dates, and replaces them with your chosen standard format. This example targets .txt files, but you can adjust the file filter to match your needs (e.g., .csv, .md).
# -------------------------- # Configure these variables! # -------------------------- $targetFiles = "C:\Your\Target\Directory\*.txt" # Path to your files (use *.ext for all files of a type) $outputFormat = "ISO8601" # Choose either "ISO8601" or "YYYYMMDD" # Get all files in the target path $files = Get-ChildItem -Path $targetFiles -File foreach ($file in $files) { Write-Host "Processing file: $($file.Name)" -ForegroundColor Cyan # Read the entire file content as a single string (better for multi-line dates) $content = Get-Content -Path $file.FullName -Raw # Regex pattern to match all our target date formats # Breakdown: # - \d{2}-\d{2}-\d{4}: Matches MM-dd-yyyy (e.g., 10-24-2007) # - [A-Za-z]{3}-\d{2}-\d{2}: Matches MMM-dd-yy (e.g., Oct-24-07) # - [A-Za-z]{3}-\d{2}: Matches MMM-yy (e.g., oct-07) $datePattern = '(?:\d{2}-\d{2}-\d{4})|(?:[A-Za-z]{3}-\d{2}-\d{2})|(?:[A-Za-z]{3}-\d{2})' # Replace every matched date with the standardized format $updatedContent = [regex]::Replace($content, $datePattern, { param($match) $convertedDate = Convert-DateToStandardFormats -InputDate $match.Value return $convertedDate.$outputFormat }) # Save the updated content back to the file (or use -DestinationPath to create a copy!) $updatedContent | Set-Content -Path $file.FullName -Encoding UTF8 Write-Host "✅ Updated $($file.Name)" -ForegroundColor Green } Write-Host "`nBatch processing complete!" -ForegroundColor Green
Key Tips for Safe Usage
- Backup First: Always make a copy of your files before running batch scripts like this. If you don't want to overwrite originals, replace the
Set-Contentline with something like:$updatedContent | Set-Content -Path "$($file.DirectoryName)\$($file.BaseName)_updated$($file.Extension)" -Encoding UTF8 - Add More Formats: If you have other date variants (e.g.,
dd/MM/yyyy), just add the format string to the$dateFormatsarray in the function, and update the regex pattern to match it. - Locale Adjustments: If your month abbreviations are in a non-English language, replace
[System.Globalization.CultureInfo]::InvariantCulturewith the appropriate culture (e.g.,[System.Globalization.CultureInfo]::GetCultureInfo('fr-FR')for French).
内容的提问来源于stack exchange,提问作者Claudia Friedel

