根据文件名中的日期归档文件。 Powershell 脚本

Archiving files according to date in file name. Powershell script

我正在尝试制作简单的 powershell 脚本来归档每天收到的文件。每个文件的名称开头都有日期,例如:20211220_Something.csv, 20211220_SomethingElse.txt, 20211219_Something.csv, 20211219_SomethingElse.txt 等...

我想制作脚本,从以下特定目录收集所有扩展名为(*.txt、*.csv、*.xslx)的文件:

\Main\Files\Main\Files\SecondaryFiles

并将具有上述扩展名的所有文件存档到例如 \Main\Files\archive21.12.zip

其中 2021、12 和 20.12 是文件名前缀中提供的日期元素。在 20.12.zip 中,我们有来自 \Main\Files 的所有文件,目录名为“SecondaryFiles”,其中有来自 \Main\Files\SecondaryFiles 的所有文件。存档后我想删除我刚刚压缩的所有文件。

现在我有这段代码循环遍历 \Main\ 目录中的所有文件并提取日期前缀。我试过使用 [Datetime]::parseexact() 方法,但自从我循环 returns 整个路径后它就不起作用了。有人知道如何解决这个问题吗?

$Date = Get-Date
$Day = $Date.Day
$Month = Date.Month
$Year = $Date.Year
$directoryPath = "\Main\Files\archive'"+$Year+"\"+$Month
$files = Get-ChildItem -Path "\Main\Files" -Include *.txt, *.csv, *.xlsx -Recurse
for ($i=0; $i -lt $files.Count; $i++){
$temp = $files[$i].FullName.split("_")[1]
}

if(!Test-Path -path $directoryPath){
    New-Item -ItemType directory -Path $directoryPath
}

Compress-Archive -Path "\Main\Files", "\Main\Files\*.txt", "\Main\Files\*.csv", "\Main\Files\*.xlsx", "\Main\Files\SecondaryFiles\*.txt", "\Main\Files\SecondaryFiles\*.csv", "\Main\Files\SecondaryFiles\*.xlsx" -Update -DestinationPath "\Main\Files\archive$Year$Month$Day.$Month.zip"

然后我从原始目录中删除项目。

另外值得一提的是,我无法确定文件夹是否仅包含今天日期的文件。因此,当整个星期都有文件时,脚本应该可以正常工作让我们说 2021121420211220

所以我又想像上面那样压缩存档文件,但是今天的日期路径将包含从文件名前缀中提取的日期。

使用 Group-Object 将具有相同日期前缀的所有文件组合在一起,并使用它来创建输出子目录、最终的 .zip 文件以及在压缩后删除原始文件。

$sourcePath  = '\Main\Files'
$destination = '\Main\Files\archive'

Get-ChildItem -Path $sourcePath -Include '*.txt', '*.csv', '*.xlsx' -Recurse |
# select only files that start with 8 digits followed by an underscore
Where-Object { $_.BaseName -match '^\d{8}_' } |
# group the files on the date part and loop trhough these groups
Group-Object { $_.BaseName.Substring(0,8) } | ForEach-Object {
    # split the date part into variables. Automatic variable $_ represents one Group, 
    # so we can take that group's Name to split into date parts 
    $year, $month, $day = $_.Name -split '(\d{4})(\d{2})(\d{2})' -ne ''
    # construct the target folder path for the zip file
    $targetPath = Join-Path -Path $destination -ChildPath ('{0}\{1}' -f $year, $month)
    # create the new sub directory if it does not yet exist
    $null = New-Item -Path $targetPath -ItemType Directory -Force
    # create the full path and filename for the zip file
    $zip = Join-Path -Path $targetPath -ChildPath ('{0}.{1}.zip' -f $day, $month)
    # compress the files in the group  
    Compress-Archive -Path $_.Group.FullName -DestinationPath $zip -Update

    # here is where you can delete the original files after zipping
    $_.Group | Remove-Item -WhatIf
}

请注意,我已将开关 -WhatIf 添加到 Remove-Item cmdlet。这是一个安全开关,所以您实际上还没有删除任何东西。该 cmdlet 现在仅显示 删除的内容。一旦您对此输出感到满意,请删除 -WhatIf 开关以便删除文件。