
前些时间下载了 全国小学、初中和高中全科全版本的教材,需要按照目录对文件做重命名处理,比如 D:\电子课本教科书\初中\语文\统编版\7年级上册.pdf 重命名为 初中_语文_统编版_7年级上册.pdf
脚本代码
# 设定根目录
$rootDirectory = "D:\电子课本教科书\"
# 设定移除目录
$yichu = "D:\电子课本教科书\"
# 获取根目录下的所有文件(递归)
$files = Get-ChildItem -Path $rootDirectory -Recurse -File
foreach ($file in $files) {
# 获取文件的完整路径
$fullPath = $file.FullName
# 从完整路径中移除根目录部分,得到相对路径(包括文件名)
$relativePathWithFileName = $fullPath -replace [regex]::Escape($yichu), ""
# 分割相对路径以获取目录部分(不包括文件名)
$relativePathDirs = [System.IO.Path]::GetDirectoryName($relativePathWithFileName)
# 如果相对路径以目录分隔符开头,则去除它
if ($relativePathDirs.StartsWith("\")) {
$relativePathDirs = $relativePathDirs.Substring(1)
}
# 将目录部分的路径分隔符替换为下划线(或其他分隔符),并作为前缀
$newPrefix = $relativePathDirs -replace "\\", "_"
# 如果前缀非空,则在前缀和原始文件名之间添加一个分隔符(可选)
if (![string]::IsNullOrEmpty($newPrefix)) {
$newPrefix += "_"
}
# 生成新的文件名(前缀+原始文件名)
$newFileName = "$newPrefix$($file.Name)"
# 生成新的完整路径(实际上只是更改了文件名,目录保持不变)
$newFilePath = Join-Path $file.Directory.FullName $newFileName
# 输出旧路径和新路径以进行调试
Write-Output "CCCiTU Old Path: $fullPath"
Write-Output "CCCiTU New Path: $newFilePath"
# 如果新路径与旧路径不同,则重命名文件
if ($newFilePath -ne $fullPath) {
Rename-Item -Path $fullPath -NewName $newFileName -Force
}
}
# 脚本结束
Write-Output "Renaming complete."
使用方法
假设在 D 盘根目录新建文本文档,将代码复制粘贴,然后把文件名改为 cccitu-mulu.ps1 (注意,原文件txt后缀,将变为.ps1)
打开Windows 自带的 PowerShell 分别执行如下命令:
cd D:\ .\cccitu-mulu.ps1



暂无评论
要发表评论,您必须先 登录