Search code examples
powershellpowershell-2.0powershell-3.0powerbi

How to parse file name in powerShell


This is the name of my file myregistration_20180105041258_NOTIFICATION_1.zip and 20180105041258 the numbers are a timestamp. I've so many files of this format. These files will be posted to my share path every day. I've automated to download all the files. But I want to download daily files with help of date. Can anyone suggest me how can I do this using power shell???


Solution

  • If I have got this right, then your requirement is to change the numbers(in the file names) which are actually a timestamp, into a datetime format and the use this to download the files or do whatever operation you deem to.

    For that, I would use the -split parameter to get the number from the filename and then convert the number into datetime format using the PoSh ParseExact function. The code will look something like this.

    $string = " myregistration_20180105041258_NOTIFICATION_1.zip"
    $array = @($string.Split('_'))
    $datetime = [datetime]::parseexact($array[1], 'yyyyMMddhhmmss', $null)
    

    Now your $datetime variable will contain the date of the corresponding file and you can use this to proceed further. If you have a bunch of files, you can loop through each of them using a foreach loop.