[英]How to rename files within subfolder to the parent directory and retain file extension - Powershell
[英]How to rename files within subfolder to the parent directory Powershell
我在运行允许子文件夹中的文件从其父目录命名的循环时遇到问题。 我目前的文件结构如下:
C:\test data
Folder 1
12345676.txt
35234443.mp4
23432234.avi
Folder 2
56859522.txt
35234443.mp4
23432234.avi
想要的最终结果。
C:\test data
Folder 1
Folder 1.txt
Folder 1.mp4
Folder 1.avi
Folder 2
Folder 2.txt
Folder 2.mp4
Folder 2.avi
这是我正在尝试修改的代码
$path = "C:\test data"
Get-ChildItem $path -Directory | Foreach-Object {
$file = $_.Fullname
$file = $file -replace ('4K','')
$file = $file -replace ('\s+\[]','')
Write-Output $file
rename-Item -LiteralPath $_.FullName -NewName $file
Get-ChildItem $path
}
### Rename files in Subfolders
Get-ChildItem $path -Recurse -File | Foreach-Object {
Rename-Item -LiteralPath $_.FullName -NewName
($_.Directory.name) -ErrorAction SilentlyContinue
}
该脚本更改文件的名称,但不保留扩展名。
C:\test data
Folder 1
Folder 1 (file)
Folder 1 (file)
Folder 1 (file)
Folder 2
Folder 2 (file)
Folder 2 (file)
Folder 2 (file)
任何信息都会有很大帮助,因为我仍在学习如何在 Powershell 中编码。
我不知道你为什么要这样做。 我下面的代码仅在子文件夹中文件名的每个扩展名不同时才有效。
有很多方法可能会出错,所以我添加了一个错误操作。
同样,我不确定你会得到你想要的,但这会满足你的要求。
请运行测试。
$path = "C:\test\"
Get-ChildItem $path -Recurse -File | Foreach-Object {
Rename-Item -LiteralPath $_.FullName -NewName ($_.Directory.name + '.' + $_.name.split('.')[1]) -ErrorAction SilentlyContinue
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.