我已经从ftp服务器上下载了使用wget并强制使用ascii编码的目录树,因此现在我拥有很多文件夹和文件名,例如“ foo%C3%BC”(某些文件/文件夹已经具有正确的名称,因为它们仅带有ascii字符)。
我现在正尝试使用powershell将其转换回utf-8,我尝试编写以下行来完成此操作
Get-ChildItem C:\Users\Administrator\Desktop\folder -Recurse | select BaseName | Rename-Item -NewName {[System.Web.HttpUtility]::UrlDecode{BaseName}}
但这不起作用,并给我以下错误
Rename-Item : Cannot rename because item at '@{BaseName=filename}' does not exist.
At line:1 char:88
+ ... ect BaseName | Rename-Item -NewName {[System.Web.HttpUtility]::UrlDecode{BaseNam ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [Rename-Item], PSInvalidOperationException
+ FullyQualifiedErrorId : InvalidOperation,Microsoft.PowerShell.Commands.RenameItemCommand
一遍又一遍(我想每找到一个文件一次)。
在“选择BaseName”之后,该命令一直有效地运行到管道,因此问题出在重命名部分中。
有谁知道如何使它工作?
Kinda很晚,但我想为可能遇到此问题的人发布答案(我只是记得我在找到答案后就发布了答案)
以下代码片段正是我所需要的
Add-Type -AssemblyName System.Web;
# Get the filenames and order them to have the files first, this avoids problems when renaming them
$data = get-childitem C:\Users\Administrator\Desktop\folder -recurse | Sort-Object FullName -descending;
# Cycle every file
ForEach($dat in $data){
# Get the decoded UTF-8 name
$decoded = [System.Web.HttpUtility]::UrlDecode($dat.name);
# Rename the file if the decoded name is different than the current one
if ($dat.name -ne $decoded){ren $dat.FullName $decoded}
}
我最初使用的方法的问题在于,文件夹在包含其中的文件之前已被重命名,这意味着单个文件的路径不再正确。我通过按降序对路径列表进行排序来解决该问题,以便首先对单个文件进行重命名,并添加了仅在文件名称由于编码而更改时才对文件进行重命名的检查。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句