PowerShell - 将特定扩展移动到年/月/扩展文件夹?



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

以下结构是否可能实现?

"年\月\按扩展名" 它可以使用原始创建的日期。

所以 如果我有来自15/01/2020的"Picture.jpg",如果我有来自15/01/2020的"Document.doc",那么它应该转到:

G:20201JPGPicture.jpg
G:20201DOCDocument.doc

等等?

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

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

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

-

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

我一直在查看数据,似乎使用 Copy,如果有两个文件具有相同的文件名,它会覆盖,因此我现在调整了 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
}

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

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

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

https://learn.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
}

最新更新