我有一个包含大约 954,000 个文件的大型文件树。我需要将大量文件重命名回原始文件,从原始文件名中删除符号并替换为数字代码,即“#”替换为“0023”,并在文件名末尾添加“-modified” .
我有以下 powershell 脚本,可以成功地在文件的一个路径目标上运行。
# Define the path where you want to perform the renaming
$path = "C:\Path\To\Your\Directory"
# Get all files in the directory
$files = Get-ChildItem -Path $path -File
foreach ($file in $files) {
# Check if the file name ends with "- modify" (case-insensitive)
if ($file.Name -like "*- modify*") {
# Remove "- modify" and replace "0023" with "#" in the file name
$newFileName = $file.Name -replace "- modify", "" -replace "0023", "#"
# Construct the full path for the new file name
$newFilePath = Join-Path -Path $path -ChildPath $newFileName
# Rename the file
Rename-Item -Path $file.FullName -NewName $newFilePath
# Output the change for verification
Write-Output "Renamed file: $($file.FullName) to $newFilePath"
}
}
是否可以运行一个powershell脚本从根文件夹运行并遍历所有文件夹和嵌套文件夹以使用更正的参数修复文件夹和文件名称?
我的一些文件和路径超出了 255 个字符的文件路径限制。 powershell 在这些情况下仍然有效吗?
我尝试构建代码,但不断遇到错误:
# Define the path where you want to perform the renaming
$rootPath = "C:\Path\To\Your\Directory"
# Function to rename items based on the criteria
function Rename-Items {
param (
[string]$itemPath
)
# Get all items (files and directories) in the path
$items = Get-ChildItem -Path $itemPath
foreach ($item in $items) {
# Check if the item name contains "- modify"
if ($item.Name -like "*- modify*") {
# Remove "- modify" and replace "0023" with "#" in the item name
$newName = $item.Name -replace "- modify", "" -replace "0023", "#"
# Construct the full path for the new name
$newItemPath = Join-Path -Path $item.DirectoryName -ChildPath $newName
# Rename the item
Rename-Item -Path $item.FullName -NewName $newItemPath
# Determine if the item is a directory or file
if ($item.PSIsContainer) {
Write-Output "Renamed directory: $($item.FullName) to $newItemPath"
} else {
Write-Output "Renamed file: $($item.FullName) to $newItemPath"
}
}
}
}
# Function to recursively rename items in all nested directories
function Process-Directories {
param (
[string]$directoryPath
)
# Rename items in the current directory
Rename-Items -itemPath $directoryPath
# Get all subdirectories
$subdirectories = Get-ChildItem -Path $directoryPath -Directory
# Process each subdirectory
foreach ($subdirectory in $subdirectories) {
Process-Directories -directoryPath $subdirectory.FullName
}
}
# Start processing from the root path
Process-Directories -directoryPath $rootPath
仅使用
-Recurse
和 \\?\
来处理 最大路径长度限制 就可以大大简化您的代码。 Get-ChildItem
还已经集成了可以处理通配符的 -Filter
。另请参阅使用带有参数的延迟绑定脚本块,以更好地了解在这种情况下如何执行重命名。
# NOTE: \\?\ is important to handle Maximum Path Length
$initialPath = '\\?\C:\Path\To\Your\Directory'
Get-ChildItem -LiteralPath -Filter '*- modify*' -Recurse |
Rename-Item -NewName { $_.Name.Replace('0023', '#').Replace('- modify', '') } -Verbose