Skanderbeg
Skanderbeg

Reputation: 3

Change String date to desired format

I want to find out the date in a mail file so I can append it to the file name. To do this I read the 4 line of the mail file, which contains the date in which the mail was received. The date is written in this format in the mail:

Tue, 1 May 2018 15:56:12 +0200

I would like to have it in this format:

yyyy_mm_dd_hh_mm

This is the code that I use to change the date to make it look more like the format i want.

cd C:\Temp\Test
$date = Get-Content RemoteBackupServer.eml | Select -Index 3
$date = $date.Trim()
$date = $date -replace 'Mon, |Tue, |Wed, |Thu, |Fri, |Sat, |Sun, ',''
$date = $date -replace ' Jan ','.01.'
$date = $date -replace ' Feb ','.02.'
$date = $date -replace ' Mar ','.03.'
$date = $date -replace ' Apr ','.04.'
$date = $date -replace ' May ','.05.'
$date = $date -replace ' Jun ','.06.'
$date = $date -replace ' Jul ','.07.'
$date = $date -replace ' Aug ','.08.'
$date = $date -replace ' Sep ','.09.'
$date = $date -replace ' Oct ','.10.'
$date = $date -replace ' Nov ','.11.'
$date = $date -replace ' Dec ','.12.'
$date = $date -replace '*:\d+ ',''
Write-Host $date

And this is the result I get with my code.

1.05.2018 15:56:12 +0200

But at the last line I get an Error "FullyQualifiedErrorId : InvalidRegularExpression".

Can someone help me to get the date in the format I mentionned above?

Edit:

Here is the code to rename the files, if someone's interested:

cd C:\Temp\Test\Test2
$mails = Get-ChildItem -Filter *.eml

for ($i=0; $i -lt $mails.Count; $i++) {
    $mail = $mails[$i].FullName
    $date = Get-Content $mail | Select -Index 3
    $date = $date.Trim()
    $date = (Get-Date $date).ToString('yyyy_MM_dd_HH_mm')
    $extension = $date + '.eml'
    $mail | Rename-Item -NewName {$mail.Replace('.eml',"$extension")}
}

Upvotes: 0

Views: 59

Answers (1)

EBGreen
EBGreen

Reputation: 37730

Use Get-Date and format strings

(Get-Date 'Tue, 1 May 2018 15:56:12 +0200').ToString('yyyy_MM_dd_hh_mm')

To get 24 hour (this is covered in the link about format strings):

(Get-Date 'Tue, 1 May 2018 15:56:12 +0200').ToString('yyyy_MM_dd_HH_mm')

Upvotes: 2

Related Questions