Powershell从字符串中提取年份和月份

时间:2017-05-04 18:50:48

标签: powershell

我正在尝试完成一个允许循环访问文件夹和文件的脚本。

  1. 该脚本将导入文件并从文件中提取名称和编号。
  2. 使用名称循环通过C:\Temp文件夹找到该名称。
  3. 列出该文件夹下的所有文件并提取年份和月份。该文件如下所示,脚本从文件名中提取201705并将05个月转换为May AAA_123456789_201705021541_AAAAAA.pdf
  4. 然后,该脚本将获取MayJuneJuly等所有文件,并通过使用导入文件中的数字创建文件夹将其发送到其他文件夹。因此,例如,如果文件名中包含05,则文件夹X00000000MAY2017和文件MAY文件移动到该文件夹​​。
  5. 到目前为止已经有了下面的脚本。我能够导入文件提取信息并循环通过它,但卡在部分从文件名中提取月份和年份并将它们放在变量中。

    $data = Import-Csv -Path  C:\temp\test.txt -Header "Number","Name" -Delimiter "|"
    $Name = $data.Name
    
    foreach ($cxName in $Name) {
        $cxName = Get-ChildItem C:\temp\$cxName
    
        ForEach ($item in $cxName) {
            If ($item -match "(?<year>\d\d\d\d)(?<mon>\d\d)") {
                "$item's date is $($Matches.Year)"
            } Else {
                "$item failed to match"
            }
        }
    }
    

2 个答案:

答案 0 :(得分:0)

你在找这个吗?

$folder_name='201705';
$year_month = [datetime]::ParseExact($folder_name, "yyyyMM", $null);
$year_month;

如果是,请使用它,否则请询问确切的要求,而不是这么长的问题。我希望这有帮助

答案 1 :(得分:0)

您可以将其更改为来自get-childitem的函数调用

Param(
[string]$subject = "AAA_123456789_201705021541_AAAAAA.pdf"
)
Clear-Host

if ($subject -imatch '_([2-9][0-9]{3})(\d{2})') {
$Year   = $matches[1]
$Month  = $matches[2]
$Month = (Get-Culture).DateTimeFormat.GetMonthName($Month)
Write-Host "Extracted:`n$Month,$Year"
} else {
Write-Error "No Matches were found dog"
}