PowerShell中Copy-Item批量复制至通配符匹配目录的问题
PowerShell批量复制文件到匹配通配符的所有目录
PowerShell的Copy-Item命令无法直接在-Destination参数中使用通配符批量指定目标目录,需要先获取所有符合路径规则的目录,再逐个执行复制操作,以下是具体实现方法:
基础实现(假设目标目录已存在)
先获取所有符合C:\Users\Administrator\AppData\Roaming\MetaQuotes\Terminal\*\MQL4\Experts规则的目录,再循环复制文件:
# 获取所有目标目录 $targetDirectories = Get-ChildItem -Path "C:\Users\Administrator\AppData\Roaming\MetaQuotes\Terminal\*\MQL4\Experts" -Directory # 遍历目录并复制文件 foreach ($dir in $targetDirectories) { Copy-Item -Path "C:\Users\Administrator\Desktop\EA\MT4\EA_bot.ex4" -Destination $dir.FullName }
也可以合并为管道执行的单行命令:
Get-ChildItem -Path "C:\Users\Administrator\AppData\Roaming\MetaQuotes\Terminal\*\MQL4\Experts" -Directory | ForEach-Object { Copy-Item -Path "C:\Users\Administrator\Desktop\EA\MT4\EA_bot.ex4" -Destination $_.FullName }
健壮性版本(自动创建不存在的目标目录)
如果部分Terminal子目录下没有MQL4\Experts目录,可以先检查并创建,再复制文件:
Get-ChildItem -Path "C:\Users\Administrator\AppData\Roaming\MetaQuotes\Terminal\*" -Directory | ForEach-Object { # 拼接完整的目标目录路径 $expertDirectory = Join-Path -Path $_.FullName -ChildPath "MQL4\Experts" # 检查目录是否存在,不存在则创建 if (-not (Test-Path -Path $expertDirectory)) { New-Item -Path $expertDirectory -ItemType Directory | Out-Null } # 复制文件到目标目录 Copy-Item -Path "C:\Users\Administrator\Desktop\EA\MT4\EA_bot.ex4" -Destination $expertDirectory }
关键说明
Get-ChildItem -Directory:确保只返回目录对象,避免匹配到文件ForEach-Object/foreach循环:遍历每个目标目录,执行复制操作Join-Path:安全拼接路径,避免手动拼接出现格式错误
内容的提问来源于stack exchange,提问作者Scott Bowden
相关产品推荐
相关产品推荐

