2014-07-10 78 views
3

我正在運行中有多個環境,可以在彈出的窗口中選擇一個腳本。我碰到的唯一問題是當我想設置腳本從我創建的源函數中複製並且一次將它放到多個位置。如何將一個文件到多個文件夾複製在PowerShell中

我需要使用以下張貼幫助代碼的一部分。

$Source = Select-Boss 

$destination = 'D:\parts','D:\labor','D:\time','D:\money' 

"Calling Copy-Item with parameters source: '$source', destination: '$destination'." 

Copy-Item -Path $source -Destination $destination 

下段是怎樣的複印功能,其餘都設置在腳本,讓你有一個更好的瞭解主要部分副本是什麼。

$Source = Select-Boss 

$destination = 'D:\parts' 

"Calling Copy-Item with parameters source: '$source', destination: '$destination'." 

Copy-Item -Path $source -Destination $destination 

但是對於一個特定的部分,我需要將它複製到多個位置。我需要這樣做,因爲我不必更改已登錄的服務器並轉到其他服務器。這一切都在一個地方完成,我希望能夠讓事情變得更簡單,而不是寫一大堆小編碼去複製並保存在文件夾中。

回答

6

copy-item僅爲其參數-destination取一個值,因此您需要某種類型的循環。

假設你在多個文件夾中所需的相同文件名:

$destFolders | Foreach-Object { Copy-Item -Path $Source -dest (Join-Path $_ $destFileName) } 

應該這樣做。

+0

我會在那裏放入那部分。我確實想在多個文件夾中保留相同的文件名 – bgrif

+0

沒關係我想我需要放在哪裏。 – bgrif

2

我想你想是這樣的:

$Source = Select-Boss 

$destination = @("D:\parts","D:\labor","D:\time","D:\money") 

# Calling Copy-Item with parameters source: '$source', destination: '$destination'." 

foreach ($dir in $destination) 
{ 
    Copy-Item -Path $source -Destination $dir 
} 

此代碼是使文件夾的數組,然後遍歷每個人,你的文件複製到它。

+0

我做了你建議做的改變,但它不起作用。我所知道的是'Copy-Item:不支持給定路徑的格式。 在行:9字符:22 +拷貝項目-Path $源-Destination $ DIR + ~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~ + CategoryInfo:NotSpecified:(:) [Copy-Item],NotSupportedException + FullyQualifiedErrorId:System.NotSupportedException,Microsoft.PowerShell.Commands。CopyItemCommand' – bgrif

+0

'$ source'的值是什麼? – Ranic

+0

$ source的值是\\ ntsrv \ common \ Deployments \ Boss \ testing.txt – bgrif

0

這是我用過的最好最簡單的解決方案。

對我來說,這是一個網絡位置,但它可以用於本地系統了。

"\\foo\foo"位置包含用戶名10個文件夾。 #使用雙斜槓(它沒有顯示在計算器上點擊這裏)

dir "\\foo\foo\*" | foreach-object { copy-item -path d:\foo -destination $_ } -verbose 

您必須對網絡共享和目標文件夾的寫權限。

0

我一直在尋找smiilar解決方案bgrif在使用PowerShell從一個方向複製文件到另一個。花了相當多的時間找到,我不能。所以希望它能爲某一個工作:

1 # Copy one or more files to another directory and subdirectories 
2 $PathFrom = "W:\_server_folder_files\basic" 
3 $typeOfFiles = "php.ini", "index.html" 
4 
5 
6 $PathTo = "Z:\test" 
7 
8 $copiedFiles = get-childitem -Path $PathFrom -Name -include $typeOfFiles -Recurse 
9 
10 $directories = Get-ChildItem -path $PathTo -Name -Exclude "*.*" 
    -recurse -force 
11 
12 
13 foreach ($copiedFile in $copiedFiles) 
14 { 
15  copy-item (Join-Path $PathFrom $copiedFile) -destination $PathTo -Recurse -Force 
16 } 
17  
18  
19 foreach ($dir in $directories) 
20 { 
21 foreach ($copiedFile in $copiedFiles) 
22 { 
23  copy-item (Join-Path $PathFrom $copiedFile) -destination (Join-Path $PathTo $dir) -Recurse -Force 
24 } 
25 } 
26  
27  
28 # List all folders where were copied files to get-childitem -Path 
29 $PathTo -Name -include $typeOfFiles -Recurse 
30 
相關問題