我用这个批处理脚本 https://stackoverflow.com/a/65549119/3074564写于Mofi https://stackoverflow.com/users/3074564/mofi将文件夹移动到其他文件夹中。
@echo off
setlocal EnableExtensions DisableDelayedExpansion
%SystemRoot%\System32\tree.com
for /F "eol=| delims=" %%I in ('dir /AD /B 2^>nul') do (
set "FolderName=%%I"
setlocal EnableDelayedExpansion
set "TargetFolder=!FolderName:~0,1!"
if not "!TargetFolder!" == "!FolderName!" (
md "!TargetFolder!" 2>nul
move /-Y "!FolderName!" "!TargetFolder!\"
)
endlocal
)
%SystemRoot%\System32\tree.com
endlocal
它将当前文件夹中具有两个或多个字符的文件夹移动到子文件夹中,子文件夹的名称是要移动的文件夹的第一个字符,并自动创建目标文件夹(如果不存在)。
但如果文件夹名称包含一个或多个 Unicode 字符,则批处理脚本将不起作用。
PowerShell 有解决方法吗?
例如,它不会移动第一个字符为的文件夹Ш
(西里尔大写字母 SHA)放入名为的文件夹中Ш
.
是的,PowerShell 可以正确处理文件路径(以及一般情况)中的 Unicode 字符。
PowerShell 中的批处理文件代码的等效项是:
Get-ChildItem -Directory -Path ??* |
Move-Item -Destination {
# Determine the target dir - the input dir's first letter -
# ensure that it exists, and output it.
New-Item -Type Directory -Force (Join-Path $_.Parent.FullName $_.Name[0])
} -WhatIf
注:-WhatIf通用参数 https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_commonparameters#whatif在上面的命令中previews the move手术。消除-WhatIf
一旦您确定该操作将按照您的要求进行。然而,即使有
-WhatIf
the 目标目录已创建马上。
-
Get-ChildItem https://learn.microsoft.com/powershell/module/microsoft.powershell.management/get-childitem -Directory -Path ??*
获取名称至少由以下组成的所有目录2人物。
- 兼容性说明:如Mofi https://stackoverflow.com/users/3074564/mofi问题中批处理文件代码的原作者指出,
-Directory
switch 需要 PowerShell 版本 3 或更高版本,并且要使代码在 v2 中也能工作,
Get-ChildItem -Path ??* | Where-Object { $_.PSIsContainer }
必须使用。
-
The Move-Item https://learn.microsoft.com/powershell/module/microsoft.powershell.management/move-item命令使用延迟绑定脚本块 https://stackoverflow.com/a/52807680/45375确定每个输入目录的目标(目标)目录:
-
New-Item https://learn.microsoft.com/powershell/module/microsoft.powershell.management/new-item -Type Directory
either creates目标目录或 - 感谢-Force
返回一个现有的一个。在这两种情况下,System.IO.DirectoryInfo https://learn.microsoft.com/en-US/dotnet/api/System.IO.DirectoryInfo实例是输出,它告诉Move-Item
将输入目录移动到哪里。在眼前。
-
Join-Path https://learn.microsoft.com/powershell/module/microsoft.powershell.management/join-path determines the full target path from the input directory's own (parent) directory, $_.Parent.FullName
[1], and the first-letter-of-the-input-dir-name target name, $_.Name[0]
)
- 注意:如果您在current目录,所以在这种情况下你可以简化为
New-Item -Type Directory -Force $_.Name[0]
[1] You can also use $_.PSParentPath
, but, due to a bug in Join-Path
in PowerShell [Core] as of 7.1, that wouldn't work on Unix-like platforms - see GitHub issue #14538 https://github.com/PowerShell/PowerShell/issues/14538.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)