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

发布于:2024-03-11 ⋅ 阅读:(135) ⋅ 点赞:(0)

在PowerShell中,如果你要在本地机器和远程Windows服务器之间拷贝文件,可以使用Copy-Item命令配合Invoke-Command(对于远程执行)或New-PSSession(用于创建持久会话后传输文件)。这里是一个使用Copy-Item通过临时会话远程拷贝文件的例子:

# 定义远程服务器信息
$remoteComputerName = "RemoteServer"
$credential = Get-Credential -UserName "username" -Message "Enter the password"

# 指定要复制的本地文件路径和远程目标路径
$localFilePath = "C:\Local\File.txt"
$remoteFolderPath = "C:\Remote\Path"

# 创建一个临时PSSession并复制文件
$session = New-PSSession -ComputerName $remoteComputerName -Credential $credential
Copy-Item -Path $localFilePath -Destination "$($remoteFolderPath)\File.txt" -ToSession $session

# 关闭PSSession
Remove-PSSession $session

如果远程服务器已经配置了WinRM服务,并且允许无交互式登录,上述脚本将能够正常工作。

另外,如果远程服务器启用了PSRemoting且信任源主机,你也可以直接使用如下命令进行单次操作而不必创建会话:

# 定义远程服务器信息
$remoteComputerName = "RemoteServer"
$credential = Get-Credential -UserName "username" -Message "Enter the password"

# 指定要复制的本地文件路径和远程目标路径
$localFilePath = "C:\Local\File.txt"
$remoteFolderPath = "C:\Remote\Path"

# 直接通过Invoke-Command进行远程拷贝
Invoke-Command -ComputerName $remoteComputerName -Credential $credential `
    -ScriptBlock {
        param($localPath, $remotePath)
        Copy-Item -Path $using:localPath -Destination "$remotePath\File.txt"
    } -ArgumentList @($localFilePath, $remoteFolderPath)

注意:在生产环境中,请确保你的凭据管理和网络访问策略符合安全规范。


网站公告

今日签到

点亮在社区的每一天
去签到