Moving Files based on name

I have a file that is written to a local directory and I would like to move that to a network drive based on its name.

The file has a set file name in the format of ReportName_MM-DD-YY.txt I would like to try and move that file to a folder named \MonthName\ReportName_MM-DD-YY.txt

I am breaking down the code and trying to see if I can extract the month from the file name but seem to be failing at that first task.

 

GetMonth(
    $FileName = "Report_10-28-20.txt"
    )
    Clear-Host
    
    if ($FileName -imatch '_([2-9][0-9]{3})(\d{2})') {
    $Month  = $matches[2]
    $Month = (Get-Culture).DateTimeFormat.GetMonthName($Month)
    Write-Host "Extracted:`n$Month"
    } else {
    Write-Error "Go back to the books your Regex failed!"
    }

The problem with your regex pattern seems to be two folder. You’re looking for a number 2-9 followed by 3 numbers 0-9. The other issue is this doesn’t account for the dash between them. You can also used named capture groups to more clearly define the intentions.

GetMonth(
    $FileName = "Report_10-28-20.txt"
    )
    Clear-Host
    
    if ($FileName -imatch '_(?<Month>\d{2})-(?<Day>\d{2})-(?<Year>\d{2})') {
        $Month = (Get-Culture).DateTimeFormat.GetMonthName($matches.Month)
        Write-Host "Extracted month:`n$Month"
    } else {
        Write-Error "Go back to the books your Regex failed!"
    }

Deleted.

LOL I missed what was in the post that required being reported. Now I’m curious… :slight_smile:

Nothing exciting. The deleted post was mine. I meant to type the text in the report box but posted a reply instead.

If you look at nickdickinson16’s post history the comments are just generic comments that could be real but actually add nothing to the threads they’re contributing to. The strange comments, the format of the username, and the fact that the firstname and lastname don’t match the display name all point to this account being a bot gearing up to post spam so I reported it.

 

Ahh yes I saw the other posts too.

[quote quote=266630][/quote]

Thank you for explaining the error in the code as well as using a better method for the named capture groups, I for sure need to go back to the books on regex, If you know a good beginner guide to regex please let me know.

Now I can extract the file name of the file I will move on the next step in the code to move the file, and will see how I get along but expect another post in the future thanks again for your help.