powershell - PowerShell - 将特定扩展移动到年/月/扩展文件夹?
问题描述
我有一个旧的外部驱动器 (F:),里面有很多文件夹和文件。我想将所有文件移动到新驱动器 (G:)。
下面的结构可以实现吗?
"Year\Month\by Extension" 可以使用原来创建的日期..
所以如果我有“ Picture.jpg
” 15/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”,这样当我查看它们时,我实际上可以检查它是否真的是重复的?非常感谢。
解决方案
这可以相当简单地实现Get-ChildItem
# 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
}
推荐阅读
- java - Janusgraph 库无法在 kerberos 环境中与 hbase 通信(无法指定服务器的 Kerberos 主体名称)
- jquery - 使用jquery根据数据属性中的最小值和最大值选择div
- sql - 在 SQL 中设置自定义请求标头,查询期望在标头中传递会话的 REST API
- gradle - 如何使用 -P 将命令行参数传递给 build.gradle 脚本并将该参数用作依赖包
- jquery - Photoshop 2015 扩展无法访问所有数组项
- django - 尽管模板文件夹中存在 Django 模板,但未找到它
- node.js - 使用 Puppeteer 拦截文档下载并提取 CSV 数据
- javascript - 调试显示更多显示更少按钮 - 缺少文本段落
- linux-kernel - 不同 ebpf 程序类型之间的地图共享
- c# - 刷新页面时 AuthorizeAttribute 不起作用