Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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/"

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading