powershell远程拷贝文件到windows 服务器

打印 上一主题 下一主题

主题 538|帖子 538|积分 1614

在PowerShell中,如果你要在本地机器和远程Windows服务器之间拷贝文件,可以使用Copy-Item下令配合Invoke-Command(对于远程执行)或New-PSSession(用于创建长期会话后传输文件)。这里是一个使用Copy-Item通过临时会话远程拷贝文件的例子:
  1. # 定义远程服务器信息
  2. $remoteComputerName = "RemoteServer"
  3. $credential = Get-Credential -UserName "username" -Message "Enter the password"
  4. # 指定要复制的本地文件路径和远程目标路径
  5. $localFilePath = "C:\Local\File.txt"
  6. $remoteFolderPath = "C:\Remote\Path"
  7. # 创建一个临时PSSession并复制文件
  8. $session = New-PSSession -ComputerName $remoteComputerName -Credential $credential
  9. Copy-Item -Path $localFilePath -Destination "$($remoteFolderPath)\File.txt" -ToSession $session
  10. # 关闭PSSession
  11. Remove-PSSession $session
复制代码
如果远程服务器已经配置了WinRM服务,并且允许无交互式登录,上述脚本将可以或许正常工作。
别的,如果远程服务器启用了PSRemoting且信任源主机,你也可以直接使用如下下令举行单次操纵而不必创建会话:
  1. # 定义远程服务器信息
  2. $remoteComputerName = "RemoteServer"
  3. $credential = Get-Credential -UserName "username" -Message "Enter the password"
  4. # 指定要复制的本地文件路径和远程目标路径
  5. $localFilePath = "C:\Local\File.txt"
  6. $remoteFolderPath = "C:\Remote\Path"
  7. # 直接通过Invoke-Command进行远程拷贝
  8. Invoke-Command -ComputerName $remoteComputerName -Credential $credential `
  9.     -ScriptBlock {
  10.         param($localPath, $remotePath)
  11.         Copy-Item -Path $using:localPath -Destination "$remotePath\File.txt"
  12.     } -ArgumentList @($localFilePath, $remoteFolderPath)
复制代码
留意:在生产环境中,请确保你的凭据管理和网络访问策略符合安全规范。






免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

石小疯

金牌会员
这个人很懒什么都没写!

标签云

快速回复 返回顶部 返回列表