在创build几个基于PowerShell的部署脚本时,我非常想念通过Powershell Remoting快速将文件传输到另一台服务器(如因特网)的简单方法,就像scp for linux一样。 幸运的是可以通过Powershell Remoting激活。 我忽略了什么?
您可以使用Invoke-Command和Set-Content通过PSRemoting会话轻松地复制文件Set-Content :
$Session = New-PSSession -ComputerName "remotehost.domain.tld" -Credential (Get-Credential) -UseSsl $FileContents = Get-Content -Path 'C:\path\to\arbitrary.file' Invoke-Command -Session $Session -ScriptBlock { param($FilePath,$data) Set-Content -Path $FilePath -Value $data } -ArgumentList "C:\remote\file\path.file",$FileContents
PowerShell 5.0新增function: Copy-Item现在带有-ToSession和-FromSession参数!
更多细节和示例在这里: 复制到或从PowerShell会话
Oneliner为你。 适用于任何版本。 传输二进制文件,如果你想。
把文件:
Invoke-Command -ComputerName "myserver.somewhere.net" -Credential (Get-Credential) -ScriptBlock {[io.file]::WriteAllBytes($Args[0],$Args[1])} -ArgumentList "c:\remote.file.path",(get-content "c:\local.file.path" -encoding byte -Read 0)
获取文件(variables没有被剥离):
[io.file]::WriteAllBytes("$localfile",(Invoke-Command -ComputerName $remotehost -Credential $usercred -ScriptBlock {get-content $Args[0] -encoding byte -Read 0} -ArgumentList "$remotefile"))