dwwilson66
dwwilson66

Reputation: 7066

How do I parse and work with a date from a filename in Powershell?

I have a series of log files into which I need to insert day-of-week. For instance, LOG-20141106-0000.TXT becomes LOG-20141106-THR-0000.TXT.

I found this question which convinces me I don't know what I'm doing as well as I thought; it's been a while since I used powershell.

So far, I've got this to rename the files, but I'm looking for the piece that'll pull the date, allow me to interpolate the day-of-week and insert that as appropriate.

$txtPath = "h:\logs"     #source files
$txtPath2 = "h:\logs\new"   #renamed files

Get-ChildItem $txtPath | foreach { 
    Move-Item $txtPath $txtPath2 ($_.Name -replace 'LOG','CLOG') 
}

I'm having a hard time pulling the date using this:

$file = Get-ChildItem $txtpath | 
Sort-Object { [DateTime]::ParseExact($_.BaseName.Substring(6,8),'yyyyMMdd',$null) } |
Select-Object -Last 1

receiving an error that the start index cannot be longer than the length of the string. H:\logs (where I feel I'm pointing) has five files named CLOG-20141031-9999.TXT where 9999 is a different serial number for each file.

What am I doing wrong?

Upvotes: 0

Views: 3964

Answers (1)

Matt
Matt

Reputation: 46710

ParseExact needs to be told the string that it needs to parse as well as how its formatted. You have $_.BaseName.Substring(6,8) and yyyyMMdd respectively. So you are asking ParseExact to convert 8 characters starting at postition 6. In practice we can see this:

"CLOG-20141031-9999.TXT".Substring(6,8)
0141031-

Which would not parse well and is most likely making the Sort-Object fail in its intention

"CLOG-20141031-9999.TXT".Substring(5,8)
20141031

Substring starts with postition 0 so the 6th character is in position 5. Update your Substring and that should be a step in the right direction. That should be the source of your issue.

Then depending on what you needed to accomplish with the week day you could use something like this.

PS M:\Scripts> ([string]([DateTime]::ParseExact("CLOG-20141031-9999.TXT".Substring(5,8),'yyyyMMdd',$null)).DayOfWeek).SubString(0,3)
Fri

If the files are always formatted with the date after the first hyphen a -split would work just as well for the date extraction as is a little more resilient to changes in the name length.

"CLOG-20141031-9999.TXT".Split("-")[1]
20141031

Upvotes: 3

Related Questions