有人可以支持使用 Powershell 重命名文件和文件内的内容吗:
ls | Rename-Item -NewName {$_ -replace 'uvw', 'xyz' }
。需要添加什么才能涵盖大写和/或混合字母?以及如何将其包含在下面的脚本中以一次性重命名所有子文件夹中的所有文件?根据此处有关该主题的其他帖子尝试了一些包括其他参数,但偶然发现了访问被拒绝的问题和其他问题。仅当使用以下脚本为
$filePath
提供单独的子文件夹时,它才起作用 - 排除提到的额外要求。请提供有关使其满足上述要求的建议:
$filePath = "C:\root_folder"
Get-ChildItem $filePath -Recurse | ForEach {
(Get-Content $_ | ForEach { $_ -creplace 'abc_123', 'def_123' }) |
Set-Content $_
}
PowerShell运算符默认是不区分大小写的,包括
-replace
,所以不区分大小写的匹配不需要额外的努力:例如'uVw' -match 'uvw'
就是$true
.
-creplace
变体(c
前缀,也可以应用于其他运算符,例如 -match
(-cmatch
) 和 -eq
(-ceq
) ,表示区分大小写)。如果您想在递归 Get-ChildItem
调用中仅处理
文件,请添加
-File
开关。
Get-Content
调用会导致 Windows PowerShell 中出现“拒绝访问”错误(该错误消息已在 PowerShell 中得到改进) (核心)7+).因此,您可能正在寻找类似以下内容的内容:
$filePath = "C:\root_folder"
Get-ChildItem -File $filePath -Recurse |
Rename-Object -WhatIf -PassThru -NewName { $_.Name -replace 'uvw', 'xyz' } |
ForEach-Object {
# NOTE: You may have to use an -Encoding argument here to ensure
# the desired character encoding.
($_ | Get-Content -Raw) -replace 'abc_123', 'def_123' |
Set-Content -NoNewLine -LiteralPath $_.FullName
}
-WhatIf
常用参数预览操作。删除 -WhatIf
并在确定操作将执行您想要的操作后重新执行。