【问题标题】:Powershell move folders content to another foldersPowershell 将文件夹内容移动到另一个文件夹
【发布时间】:2021-11-29 02:18:16
【问题描述】:

我两周前开始学习 powershell。我有以下文件夹结构

C:\not prepared\Not ready
    ABCD_EFGH-whatever\work
    IJK-whatever\work
    LMN-whatever\work
    OPRSTU_WXYZ-whatever\work

C:\Already ready
    ABCD_EFGH
    IJK
    LMN
    OPRWXY

脚本将从C:\Already ready 运行。我想将每个work 文件夹从"Not ready\*\" 移动到"Already ready\*" 以获得

C:\not prepared\Not ready
    ABCD_EFGH-whatever
    IJK-whatever
    LMN-whatever
    OPRSTU_WXYZ-whatever

C:\Already ready
    ABCD_EFGH\work
    IJK\work
    LMN\work
    OPRWXY\work

我不想指定确切的文件夹名称,因为这些名称可能会改变。只有来自 Not ready 和 Already ready 子文件夹的前 3 个字符匹配。我想我应该从两个位置读取所有子文件夹的名称,然后将它们放在一个数组中并一一比较名称。此外,并非所有文件夹都可能始终存在于C:\not prepared\Not ready 中。

有更聪明的方法吗?请给我一个提示或例子。

【问题讨论】:

    标签: powershell variables subdirectory


    【解决方案1】:
    Get-Item 'C:\not prepared\Not ready\*\work' | ForEach-Object {
    
      # Derive the destination dir's name from the parent directory name,
      # by taking the string before "-". To also split by "_", use:
      #    $destDir = ($_.Parent.Name -split '[-_]')[0] 
      # To take just the first 3 characters, use:
      #    $destDir = $_.Parent.Name.Substring(0, 3)
      $destDir = ($_.Parent.Name -split '-')[0]
    
      # Handle the lone exception to the name mapping.
      if ($_.Parent.Name -like 'OPRSTU_WXYZ-*') { $destDir = 'OPRWXY' }
    
      # Make sure that the destination dir. exists.
      $null = New-Item -ErrorAction Stop -Force -Type Directory $destDir
    
      # Perform the move.
      $_ | Move-Item -Destination $destDir -WhatIf
    
      # If desired, remove the parent dir. of the source dir.
      Remove-Item -LiteralPath $_.Parent.FullName -Recurse -Force -WhatIf
    }
    

    注意:上面命令中的-WhatIf common parameter预览操作。一旦您确定该操作会执行您想要的操作,请删除 -WhatIf。

    注意:上面的解决方案假设了两件事:

    • 每个源 work 文件夹唯一映射到目标文件夹。

    • 如果目标文件夹恰好已经存在,则假定它还没有work 子文件夹。

    【讨论】:

    • 非常感谢。它工作得很好。我将在循环外处理 OPRSTU_WXYZ-whatever\work ->OPRWXY\work 异常。一旦我变得更有经验,我将尝试从文件夹名称中提取前 3 个字符并修改代码
    • 感谢您的提示。我只想比较 C:\not Prepared\Not ready\\work 中的前 3 个字符与 C:\Already ready\ 中的前 3 个字符,以匹配正确的文件夹。但是,从 OPRSTU_WXYZ-whatever 复制到 OPRWXY 文件夹而不更改文件夹名称。我知道它设计得很糟糕
    • 我在想:用目标文件夹构建一个哈希表(已经准备好了)。使用前三个字母作为键。然后,您可以在枚举源文件夹时查找 dest 文件夹 - 如果哈希表中不存在 dest,则根据源名称创建一个新文件夹。
    • @qcjuzzqq,如果你想删除每个work 目录的父目录。在源头,您可以更简单地使用Remove-Item -LiteralPath $_.Parent.FullName -Recurse -Force
    • @Palansen,这里没有both。只需将OPRSTU_WXYZ-whatever\work 移动到OPRWXY\work,作为异常 名称映射。再说一遍:这个答案不是试图为潜在的名称映射冲突提供解决方案 - 因为这超出了问题的范围。但是,我已经更新了答案以澄清限制和假设。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-11-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-10-25
    相关资源
    最近更新 更多