powershell - 如何将文件夹移动到具有要移动的文件夹的第一个字符名称的子文件夹中,并支持文件夹名称中的 Unicode 字符?

标签 powershell

我使用batch script编写的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 common parameter 预览移动操作。一旦您确定该操作将执行您想要的操作,请删除 -WhatIf。然而,即使有
-WhatIf目标目录立即创建

  • Get-ChildItem -Directory -Path ??* 获取名称至少由 2 个字符组成的所有目录。

    • 兼容性说明:正如问题中批处理文件代码的原始作者 Mofi 指出的那样,-Directory 开关需要 PowerShell 版本 3 或更高版本,才能使代码在v2 也是如此,
      获取-ChildItem -Path ??* |必须使用Where-Object { $_.PSIsContainer }
  • Move-Item 命令使用 delay-bind script block 来确定每个输入目录的目标(目标)目录:

    • New-Item -Type Directory 要么创建目标目录,或者 - 借助 -Force 返回一个现有目录.在这两种情况下,都会输出一个 System.IO.DirectoryInfo 实例,它告诉 Move-Item 将输入目录移动到哪里。就在手边。

    • Join-Path 从输入目录自己的(父)目录 $_.Parent.FullName[1] 确定完整目标路径,以及第一个 -输入目录名称字母目标名称,$_.Name[0])

      • 注意:如果您在当前目录中运行命令,则构造完整的目标路径并不是绝对必要的,因此在这种情况下,您可以简化为
        New-Item -Type Directory -Force $_.Name[0]

[1] 您还可以使用 $_.PSParentPath,但是,由于自 7.1 起 PowerShell [Core] 中的 Join-Path 存在错误,这在类 Unix 平台上不起作用 - 请参阅 GitHub issue #14538

关于powershell - 如何将文件夹移动到具有要移动的文件夹的第一个字符名称的子文件夹中,并支持文件夹名称中的 Unicode 字符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65564448/

相关文章:

powershell - 如何在powershell中合并两个具有相同标题的csv文件并丢弃重复的行

excel - 使用 PowerShell 在 Excel 文档中插入空行

powershell - 具有用户帐户启用状态的 Get-ADGroupMembers

powershell - 新对象 : The term New-Object is not recognized as the name of a cmdlet

PowerShell - 批量更改文件编码为 UTF-8

powershell - 即使没有比赛也能获得一场比赛

rest - 如何使用 VSTS REST API 对新构建进行排队

windows - 自动安装 IIS

powershell - 运行外部程序 - 'Start-Process' 和 '&' 之间的差异

powershell - IF 语句在 Powershell 中不起作用