Home > Enterprise >  What is the best way to replace a portion of string with PowerShell -replace
What is the best way to replace a portion of string with PowerShell -replace

Time:08-11

I was given some very long csv files and have been tasked with making the information in them readable. I want to turn time formats like 2022-08-07, 08:00:00 into a time format like 08/07/2022 8:00:00. I was looking at wild cards and was going to start with replacing the dashes with slashes first and tried -replace "(....{-}..{-}..","\1/\2/\3/" with no change to the string. I found a similar post that mentioned some regex that can helped him achieve something similar? If anyone can help me out or point me to some resources to learn more about this that would be great.

CodePudding user response:

You could do what you are describing this way:

$OldDate = '2022-08-07, 08:00:00'
if ($OldDate -match '(?<Year>\d{4})-(?<Month>\d\d)-(?<Day>\d\d), (?<Hour>\d\d):(?<Minute>\d\d):(?<Seconds>\d\d)') {
    Write-Host "$($Matches.Month)/$($Matches.Day)/$($Matches.Year) $($Matches.Hour):$($Matches.Minute):$($Matches.Seconds)"
}

But I think life would be a lot simpler to convert the string to a DateTime and then back to a string:

$OldDate = '2022-08-07, 08:00:00'
[DateTime]::ParseExact($OldDate, "yyyy-MM-dd, hh:mm:ss", $null).ToString('MM/dd/yyyy h:mm:ss')
  • Related