scriptblock中的Copy-File无法找到路径

时间:2017-02-06 15:32:25

标签: powershell powershell-v2.0 powershell-v3.0 powershell-v4.0 powershell-remoting

我已经实现了一个PS脚本,可以同时在多个服务器上部署代码。这里我需要将一些源文件从一个服务器复制到另一个服务器。请参阅以下代码:

for ($i=1; $i -le 5; $i++) {
    $serverName="iwflO" + $i
    $sourceFile="\\iwdflO1\C$\Deploy\bin"
    $destination="\\$serverName\C$\Program Files (X86)\Shian\MyService\bin\"
    $Myblock = {
        Param{$sourceFile,$destination)
         Copy-Item -Force -Recurse $sourceFile -Destination $destination
    }
    $result = Invoke-Command -ComputerName $ServerName -Credential "shian" -ScriptBlock $Myblock -ArgumentList $sourceFile,$destination;
    $result;
}
cd c:\

它适用于iwflO1,它是我运行脚本的根服务器,但对于其他服务器,它给我一个错误,如

  

找不到路径" \ iwdflO1 \ C $ \ Deploy \ bin"因为它不存在。

但是如果我登录到iwflO2或任何其他服务器并手动点击它的工作正常。

1 个答案:

答案 0 :(得分:0)

我可以看到错误在于块:

而不是:

$Myblock={param{$sourceFile,$destination)

copy-Item -Force -Recurse $sourceFile -Destination $destination
}

这样做:

$Myblock={param($sourceFile,$destination)

copy-Item -Force -Recurse $sourceFile -Destination $destination
}

如果我正在硬编码服务器名称(在我当地测试)

,这工作正常

由于您使用的是admin分享,请直接尝试:

Copy-Item -Path \\serverA\c$\programs\temp\test.txt -Destination \\serverB\c$\programs\temp\test.txt;

注意:您必须 指定文件 。否则你在源文件夹中 get-childitem -recurse 并将其直接放在目的地。

希望它有所帮助。

相关问题