首页 > 解决方案 > 将文件复制到远程服务器,在加入本地和远程服务器的路径时在PowerShell中复制文件时出现问题

问题描述

enter code here我在将文件复制到远程服务器时遇到问题,加入路径以某种方式失败。下面是代码:

Invoke-Command -ComputerName $RemoteServer -ScriptBlock {param($DestinationDir,$LocalCertResultObj,$RemoteCertResultObj,$SourceDir) Compare-Object $LocalCertResultObj $RemoteCertResultObj  -Property Name, Length, FullName   | Where-Object {$_.SideIndicator -eq "<="} | ForEach-Object {
        {$DestinationDir = Join-Path $DestinationDir $_.FullName.Substring($SourceDir.length)}
        Write-Output $DestinationDir
        Write-Output $SourceDir
      Copy-Item -Path "$SourceDir\$($_.name)" -Destination "$DestinationDir" -Recurse -Force
}   } -ArgumentList $DestinationDir,$LocalCertResultObj,$RemoteCertResultObj,$SourceDir -Credential $RemoteMachine_cred

得到如下错误:

$DestinationDir = Join-Path $DestinationDir $_.FullName.Substring($SourceDir.length)
C:\TestFolderR
C:\TestFolder
Cannot find path 'C:\TestFolder\file1.txt' because it does not exist.
    + CategoryInfo          : ObjectNotFound: (C:\TestFolder\file1.txt:String) [Copy-Item], ItemNotFoundException
    + FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.CopyItemCommand

标签: powershell

解决方案


加入路径看起来工作正常。Copy-Item的错误很明显,就是找不到C:\TestFolder\file1.txt。由于您可能正在尝试将此文件复制到远程服务器,因此您ScriptBlock使用的 with将在远程系统上Invoke-Command运行整个文件。ScriptBlock它无法通过 PowerShell 会话复制该文件,因为它不知道您的本地文件系统 - 至少,不使用Invoke-Command.

您可以建立New-PSSession远程系统,并Copy-Item直接从本地会话到远程文件系统使用它:

$Session = New-PSSession -ComputerName server.domain.tld -Credential $RemoteMachine_Cred
Copy-Item -ToSession $Session -Path $localPath-Destination $remotePath

您甚至可以将远程文件系统中的项目复制回本地系统。使用$Session我们上面建立的相同:

Copy-Item -FromSession $Session -Path $remotePath -Destination $localPath

推荐阅读