使用嵌套的foreach将用户文件夹复制到新文件夹

时间:2017-09-12 18:32:22

标签: powershell foreach robocopy

我正在尝试使用robocopy将c:\ users文件夹复制到新目标位置。我的嵌套foreach语句出现了问题:

$users = @(
    'jack'
    'Jon'
)
$news = @(
    'jacknew'
    'JonNew'
)

foreach ($userx in $users) {
    foreach ($new in $news) {
        $source = "c:\users\$($userx)"
        $destination = "d:\users\$($new)"

        robocopy $source $destination /MIR /LOG:c:\robocopy.txt /NP
    }
}

将两个文件夹复制到d:\ jacknew文件夹。

1 个答案:

答案 0 :(得分:2)

您有两个foreach循环,因此您将执行robocopy 4次:

robocopy c:\users\jack d:\users\jacknew /MIR /LOG:c:\robocopy.txt /NP
robocopy c:\users\jack d:\users\jonnew /MIR /LOG:c:\robocopy.txt /NP
robocopy c:\users\Jon d:\users\jacknew /MIR /LOG:c:\robocopy.txt /NP
robocopy c:\users\Jon d:\users\jonnew /MIR /LOG:c:\robocopy.txt /NP

如果您要将jackjon复制到相应的文件夹jacknewjonnew,您可以使用单个foreach循环,只需追加{ {1}}复制时; e.g:

new