【问题标题】:Change folder structure Year >Month based on Filename(DATE) -powershell根据文件名(日期)更改文件夹结构年>月-powershell
【发布时间】:2019-10-14 23:37:15
【问题描述】:

我正在尝试创建一个执行以下操作的脚本:

1)检查 MASTERFOLDER 内的所有子文件夹/文件

2)所有文件扩展名相同,同一天修改

Script to Create a Monthly folder and move files to it every month.

代码基于上面的问题:

# Get the files which should be moved, without folders
$files = Get-ChildItem '\\test\d$\Reports\client *' -Recurse | 
where {!$_.PsIsContainer}

# List Files and names which will be moved
$files.names

# Target Folder where files should be moved to. The script will automatically  create a folder for the year and month.
 $targetPath = '\\test\d$\Reports\client\'

foreach ($file in $files)
 {

 # Get year and Month of the file

$year = $file.LastWriteTime.Year.ToString()
$month = $file.LastWriteTime.Month.ToString("00")
$monthname = (Get-Culture).DateTimeFormat.GetAbbreviatedMonthName($month)

LastWriteTime 不起作用 - 必须根据包含日期的名称对文件进行排序 - 例如: ClientReportX 20191014 file1.csv

也许每年使用 2015 - 2019 + 月份的 -match

   $filesstructure| foreach-object (file in files) { 
   if($file.name-match '2019') {
 #MOVE TO FOLDER 2019 - >  MONTH OF FILE 
  ELSE($filename -match '2018' {
 #MOVE TO FOLDER 2018 ->  MONTH OF FILE 

.....

其余代码

# Set Directory Path
$Directory = $targetPath + "\" + $month + $monthname
# Create directory if it doesn't exsist
if (!(Test-Path $Directory))
{
New-Item $directory -type directory
}
 $file | Move-Item -Destination $Directory
 }

目标:主文件夹 > 2019 - 2015 年每年的子文件夹列表。每个文件夹年份的内部 > 1 月 - 12 月。

感谢任何帮助

【问题讨论】:

  • this >>> $Year, $Month, $Day = 'ClientReportX 20191014 file1.csv'.Split(' ')[1] -split '(....)(..)(..)' | Where-Object {$_}

标签: powershell


【解决方案1】:

您可以使用.Substring() 从如下所示的文件名中获取年、月和日。之后,您可以创建一个新的 DateTime 对象并接收月份名称。

$FileName = 'ClientReportX 20191014 file1.csv'

$Year = $FileName.Split(' ')[1].Substring(0, 4)
$Month = $FileName.Split(' ')[1].Substring(4, 2)
$Day = $FileName.Split(' ')[1].Substring(6, 2)

$MonthName = Get-Date -Year $Year -Month $Month -Day $Day -UFormat '%B'

希望日期始终采用相同的格式...此示例使用正则表达式 (About Regular Expressions) 和自动 $Matches Hashtable 变量来检索捕获的文本。

$FileName = 'ClientReportX 20191013 file1.csv'
if ($FileName -match '([12]\d{3}(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01]))') #Check with regex if date is in file name
{
    $DateFromFileName = $Matches[0] #$Matches is a default variable (Hashtable) and the matches will be stored here

    $Year = $DateFromFileName.Substring(0, 4)
    $Month = $DateFromFileName.Substring(4, 2)
    $Day = $DateFromFileName.Substring(6, 2)

    $MonthName = Get-Date -Year $Year -Month $Month -Day $Day -UFormat '%B'

    $MonthName
}

$Matches.Clear() #Clear the match

【讨论】:

  • 添加了另一个使用正则表达式提取日期的示例。所以希望日期始终采用相同的格式;-)
  • 您能否添加根据文件名 DATE 创建文件夹的步骤
猜你喜欢
  • 1970-01-01
  • 2023-03-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-10-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多