将文件复制到远程服务器的位置子目录中

时间:2017-09-19 13:40:07

标签: powershell loops foreach

我创建了一个脚本来复制远程服务器上的本地文件 远程位置是C:\ past,本地文件需要从c:\ past复制到所有子目录。 (即c:\ past \ 1,c:\ past \ 2,c:\ past3,c:\ past \ 4等等。)

    $PathFrom = "C:\ISO\ncis.exe" 
    $computers="192.168.42.117"
    foreach ($computer in $computers)
    {
     $folders = Get-ChildItem "C:\past" -Directory 
    }
   foreach ($folder in $folders.name) 
    {

     #copy-item _path $PathFrom -ToSession $TargetSession -Destination "C:\past\$folder" -Recurse -ComputerName $computers
     copy-item _path $PathFrom -ComputerName $computers -Destination "C:\past\$folder" -Recurse
      }

获得以下错误

enter Get-ChildItem : Cannot find path 'C:\past' because it does not 
exist.
At line:3 char:14
+   $folders = Get-ChildItem "C:\past" -Directory
+              ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo          : ObjectNotFound: (C:\past:String) [Get-
ChildItem], ItemNotFoundException
+ FullyQualifiedErrorId : 
PathNotFound,Microsoft.PowerShell.Commands.GetChildItemCommandcode 
here

2 个答案:

答案 0 :(得分:1)

既然你说你可以通过UNC路径来实现它,那么你应该按照自己的意愿行事......

$PathFrom = "C:\ISO\ncis.exe" 
$computers="192.168.42.117"
foreach ($computer in $computers){
     Get-ChildItem "\\$computer\C$\past" -Directory | %{ Copy-Item -path $PathFrom -Destination $_.Fullname }
}

答案 1 :(得分:0)

foreach ($folder in $folders.fullname) 

使用Fullname而不是名称。

这没有意义,它是从本地机器获取目录。

foreach ($computer in $computers)
{
 $folders = Get-ChildItem "C:\past" -Directory 
}

Copy-Item没有-ComputerName参数

copy-item _path $PathFrom -ComputerName $computers

检查示例 Microsoft Copy-Item