Другой подход заключается в использовании регулярного выражения для получения различных частей имени файла.
Возможно, что-то вроде этого:
function Split-FileName {
param ([string]$FileName)
if ($FileName -match '^(?<ip>(?:\d{1,3}_){3}\d{1,3})_(?<date>(?:\d{1,2}_){2}\d{4})_(?<time>(?:\d{1,2}_){2}\d{1,2})(?<ext>\.\w+)') {
[PSCustomObject]@{
IPAddress = $matches['ip'] -replace '_', '.'
Date = $matches['date'] -replace '_', '-'
Time = $matches['time'] -replace '_', ':'
Extension = $matches['ext'].ToUpper()
}
}
}
Используйте это так:
Split-FileName '192_168_249_1_01_22_2019_01_38_55.txt'
Чтобы вернуть объект со всеми 4 частями в требуемом формате (по умолчанию в виде таблицы)
IPAddress Date Time Extension
--------- ---- ---- ---------
192.168.249.1 01-22-2019 01:38:55 .TXT
или в виде списка, если вы сделаете
Split-FileName '192_168_249_1_01_22_2019_01_38_55.txt' | Format-List
IPAddress : 192.168.249.1
Date : 01-22-2019
Time : 01:38:55
Extension : .TXT
Regex Подробнее
^ Assert position at the beginning of a line (at beginning of the string or after a line break character)
(?<ip> Match the regular expression below and capture its match into backreference with name “ip”
(?: Match the regular expression below
\d Match a single digit 0..9
{1,3} Between one and 3 times, as many times as possible, giving back as needed (greedy)
_ Match the character “_” literally
){3} Exactly 3 times
\d Match a single digit 0..9
{1,3} Between one and 3 times, as many times as possible, giving back as needed (greedy)
)
_ Match the character “_” literally
(?<date> Match the regular expression below and capture its match into backreference with name “date”
(?: Match the regular expression below
\d Match a single digit 0..9
{1,2} Between one and 2 times, as many times as possible, giving back as needed (greedy)
_ Match the character “_” literally
){2} Exactly 2 times
\d Match a single digit 0..9
{4} Exactly 4 times
)
_ Match the character “_” literally
(?<time> Match the regular expression below and capture its match into backreference with name “time”
(?: Match the regular expression below
\d Match a single digit 0..9
{1,2} Between one and 2 times, as many times as possible, giving back as needed (greedy)
_ Match the character “_” literally
){2} Exactly 2 times
\d Match a single digit 0..9
{1,2} Between one and 2 times, as many times as possible, giving back as needed (greedy)
)
(?<ext> Match the regular expression below and capture its match into backreference with name “ext”
\. Match the character “.” literally
\w Match a single character that is a “word character” (letters, digits, etc.)
+ Between one and unlimited times, as many times as possible, giving back as needed (greedy)
)