How to pick the right file using timstamp appended file name and copy the last dropped file into another folder?

Viewed 25

I am trying to pick the right file using file name(timestamp appended in the file name).

I have 3 files: text.041922.061512, text.041922.063016, text.041922.064212. I need pick text.041922.064212 because it was created last which has data and time on the file name itself. How do i achieve this using PowerShell?

Thanks in advance. I would really appreciate it.

My script is this:

Get-ChildItem -Path "c:/demo | Sort-Object { [DateTime]::ParseExact($_.BaseName.Substring(7,13).Replace('.',' '), "MMddyy hhmmss",$null) } | Select-Object -First 1 | Copy-Item -Destination "E:/test/"
1 Answers

Your file names are missing their extension, but assuming the extension doesn't have any numeric digits, you could use -replace '\D+' to remove all non numeric digits from the file names and then the format for ParseExact could be MMddyyHHmmss.

If the files actually don't have an extension, use $_.Name instead of $_.BaseName.

Get-ChildItem -Path "c:/demo" | Sort-Object {
    [DateTime]::ParseExact(($_.BaseName -replace '\D+'), 'MMddyyHHmmss', $null)
} -Descending | Select-Object -First 1 | Copy-Item -Destination "E:/test/"

Here is an example that you can use for testing:

[System.IO.FileInfo[]]('text.041922.061512', 'text.041922.063016', 'text.041922.064212') | Sort-Object {
    [DateTime]::ParseExact(($_.Name -replace '\D+'), 'MMddyyHHmmss', $null)
} -Descending | Select-Object -Expand Name -First 1

# Returns: text.041922.064212
Related