powershell - 如果找到匹配的子目录,则需要每个子目录的脚本来执行命令
问题描述
我有兴趣将 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
解决方案
以下脚本将检查来自源的任何文件夹是否包含下划线
并在那里拆分 - 是否存在于目标中并调用 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
推荐阅读
- reactjs - React-Redux:状态变化不要调用 mapStateToProps
- reactjs - 模拟嵌套在路由器和 Provider 组件中的 this.props.dispatch
- python-3.x - 将年度时间序列转换为月度
- c++ - “如果引用专业化的上下文取决于模板参数”是什么意思?
- ruby-on-rails - 如何为非 Active Record 对象支持 Rails 可回收缓存键
- powerpivot - 计算人口月份
- django - 找不到 gunicorn.socket 的工作
- python - 如何将 python 日志记录为 Cosmos-DB 记录器?
- xcode - 运行时缺少 SwiftProtobuff.framework
- ios - Swift:隐式返回不编译?