2014-07-10 164 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 
相关问题