Regex & Substring() To Get Part of File Name

I have different types of files that all have the date in the filename (YY-MMDD), and I need to extract only the date portion and use for further execution (? = may or may not have character, depending on type of file):


The Split() method portion below works, but now I need to assign only the date portion to a variable and leave the other characters out. Though likely quite simple, I’ve tried many regex’s but my regex saw needs a lot of sharpening.

if ($FileName -match "\d{2}-\d{4}")
     $Label = $FileName.Split('.')[0]

     # assign date to variable here

Thank you for any help.


$test = @(

ForEach($item in $test)
    If($item -match "(?'date'\d{2}-\d{4})")
        "$item's date is $($Matches['date'])"
        "$item failed to match"

Just need a capturing group.

If you were using get-childitem to get the file names, there isn’t a need to use the .split(). The returned object will come with a BaseName property that already has the file type extension removed.

Thanks Craig!

That’s exactly what was needed. You can see I was essentially missing (?‘date’\d{2}-\d{4}) - another simple fix.

Appreciate the help!