如果找到匹配的子目录,则每个子目录都需要一个脚本来执行命令

时间:2018-12-21 23:53:53

标签: powershell

我对在robocopy中使用Powershell感兴趣,但是我想自己解决所有问题。如果某人感到无聊,则一定要对此进行破解。如果我违反某些规则,请提前对不起。

我有一堆子文件夹为:

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

1 个答案:

答案 0 :(得分:0)

以下脚本将检查源中是否包含下划线的任何文件夹
并在那里拆分-存在于目标位置并调用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
相关问题