首页 > 解决方案 > PowerShell - 将特定扩展移动到年/月/扩展文件夹?

问题描述

我有一个旧的外部驱动器 (F:),里面有很多文件夹和文件。我想将所有文件移动到新驱动器 (G:)。

下面的结构可以实现吗?

"Year\Month\by Extension" 可以使用原来创建的日期..

所以如果我有“ Picture.jpg15/01/2020,如果我有“ Document.doc”,15/01/2020那么它应该去:

G:\2020\01\JPG\Picture.jpg
G:\2020\01\DOC\Document.doc

等等?

我尝试了以下方法,它能够移动到一年文件夹和一个月文件夹,尽管我注意到一月份的月份文件夹的命名是 1 而不是 01:

https://www.thomasmaurer.ch/2015/03/move-files-to-folder-sorted-by-year-and-month-with-powershell/

任何帮助将不胜感激,非常感谢。

-

非常感谢您的帮助,它运行良好,我能够轻松复制所有文件。

我一直在查看数据,似乎使用 Copy,如果有两个具有相同文件名的文件,它会覆盖,因此我现在将复制命令调整为移动。我对目的地所做的一些其他更改:扩展名\年\月格式:

# Get all files
Get-ChildItem F:\ -File -Recurse | ForEach-Object {
# Get the modified date
$dt = Get-Date $_.LastWriteTime
$year = $dt.Year
$month = $dt.Month

# This adds "0" in front of the 1-9 months
if($dt.Month -lt 10) {
$month = "0" + $dt.Month.ToString() 
} else {
$month = $dt.Month
}

# Remove leading '.' from the extension
$extension = $_.Extension.Replace(".", "")

# Where we want to move the file
$destinationFolder = "G:\$extension\$year\$month\"

# Ensure full folder path exists
if(!(Test-Path $destinationFolder)) {
New-Item -ItemType Directory -Force -Path $destinationFolder
}

# Copy/Move the item to it's new home
Move-Item $_.FullName $destinationFolder
}

到目前为止,这段代码非常棒,如果可以添加以下内容 - 它将是完整的:

如果目标文件夹中已经存在“Picture.jpg”,是否可以将其添加为“Picture_1.jpg”,这样当我查看它们时,我实际上可以检查它是否真的是重复的?非常感谢。

标签: powershell

解决方案


这可以相当简单地实现Get-ChildItem

https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.management/get-childitem?view=powershell-7

# Get all files
Get-ChildItem F:\ -File -Recurse | ForEach-Object {
  # Get the creation date
  $dt = Get-Date $_.CreationTime
  $year = $dt.Year
  $month = $dt.Month

  # Remove leading '.' from the extension
  $extenstion = $_.Extension.Replace(".", "")

  # Where we want to move the file
  $destinationFolder = "G:\$year\$month\$extension\ "

  # Ensure full folder path exists
  if(!(Test-Path $destinationFolder)) {
    New-Item -ItemType Directory -Force -Path $destinationFolder 
  }

  # Copy the item to it's new home
  Copy-Item $_.FullName $destinationFolder
}

注意变量末尾的空格$destinationFolder纯粹是因为没有它,Stack Overflow 会将其余代码显示为红色字符串。在您的实现中删除它。

此外,如果您需要个位数月份的前导 0,您可以执行以下操作:

if($dt.Month -lt 10) {
  $month = "0" + $dt.Month.ToString() 
} else {
  $month = $dt.Month
}

推荐阅读