首页 > 解决方案 > 如果找到匹配的子目录,则需要每个子目录的脚本来执行命令

问题描述

我有兴趣将 Powershell 与 robocopy 一起使用,但我想自己搞清楚一切。如果有人感到无聊,请务必尝试一下。如果我违反了某些规则,我很抱歉。

我有一堆子文件夹:

C:\AB1234_randomadfasdf
C:\AB1234_otherrandomds
c:\AB1235_randomasdfgfd
C:\AB1236_randomsdfgsdf

对于这些文件夹中的每一个,如果仅找到匹配的(下面的文件夹):

D:\AB1234
D:\AB1235
D:\AB1236

我想执行一个 robocopy 命令,例如

robocopy C:\AB1234_randomadfasdf D:\AB1234\AB1234_randomadfasdf /e /z 
robocopy C:\AB1234_otherrandomds D:\AB1234\AB1234_otherrandomds /e /z 
etc

标签: powershell

解决方案


以下脚本将检查来自源的任何文件夹是否包含下划线
并在那里拆分 - 是否存在于目标中并调用 robocopy:

## Q:\Test\2018\12\22\SO_53891986.ps1

$src = 'C:\'
$dst = 'D:\'

Get-ChildItem "$src*_*" -Directory | 
  Where-Object {$_.Name -match '^(.*?)_' -and (Test-Path (Join-Path $dst $Matches[1]))} |
    ForEach-Object {
      &robocopy $_.FullName ("{0}{1}\{2}" -f $dst,$Matches[1],$_.Name) /e /z
    }

使用相同的 $src 和 $dst 运行脚本后的示例树

> tree \
├───AB1234
│   ├───AB1234_otherrandomds
│   └───AB1234_randomadfasdf
├───AB1234_otherrandomds
├───AB1234_randomadfasdf
├───AB1235
│   └───AB1235_randomasdfgfd
├───AB1235_randomasdfgfd
├───AB1236
│   └───AB1236_randomsdfgsdf
└───AB1236_randomsdfgsdf

推荐阅读