2017-09-12 100 views
0

我正在嘗試將c:\ users文件夾複製到robocopy的新目標。事情是我的嵌套foreach說法錯在這裏:使用嵌套的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文件夾中。

回答

2

你有兩個foreach循環,所以你將執行robocopy 4次:如果你想jackjon複製到相應的文件夾jacknewjonnew

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 

,你可以使用一個foreach循環,只是追加new複製時;例如:

$users = @(
    'jack' 
    'Jon' 
    ) 
    foreach ($user in $users) { 
     $source = "c:\users\$($user)" 
     $destination = "d:\users\$($user)new" 
     robocopy $source $destination /MIR /LOG:c:\robocopy.txt /NP 
    } 
+1

作爲邊注:如果目的地文件夾可以用於映射源的[哈希表(https://technet.microsoft.com/en-us/library/ee692803.aspx)到目標文件夾不能通過簡單地附加一個字符串來構造。 –

相關問題