powershell - 将文件复制到远程服务器,在加入本地和远程服务器的路径时在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
解决方案
加入路径看起来工作正常。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
推荐阅读
- javascript - Laravel 分页方法仅从数据库中获取特定的行数,而不是获取所有数据
- python - Data cleaning while Web-scraping using Beautiful soup
- typescript - 如何拒绝 TypeScript 中具有未知类型的不兼容函数参数
- javascript - 不和谐.js | 发出消息狙击命令
- vim - 在 .vimrc、ftplugin、after/ftplugin 等中设置值后,Vim 最终会应用哪种配置?
- r - R lubridate as_date 不会将日期时间转换为日期
- google-cloud-platform - 从谷歌云存储将数据流式传输到网络
- python - 将 .py 文件转换为 .exe 文件
- r - 有条件地将一列的内容复制到另一列
- asp.net-core - IFeatureCollection 已处置对象名称:任务中的集合?