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):
?YY-MMDD?.???
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.
Aaron
$test = @(
'16-0830.txt'
'randomtext16-0830.txt'
'16-0830randomtext.txt'
'randomtext16-0830randomtext.txt'
'1234516-083012345.txt'
)
ForEach($item in $test)
{
If($item -match "(?'date'\d{2}-\d{4})")
{
"$item's date is $($Matches['date'])"
}
Else
{
"$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!
Aaron