21

I just burned a couple of hours searching for a solution to send files over an active PSSession. And the result is nada, niente. I'm trying to invoke a command on a remote computer over an active session, which should copy something from a network storage. So, basically this is it:

icm -Session $s {
Copy-Item $networkLocation $PCLocation }

Because of the "second hop" problem, I can't do that directly, and because I'm running win server 2003 I cant enable CredSSP. I could first copy the files to my computer and then send/push them to the remote machine, but how? I tried PModem, but as I saw it can only pull data and not push.

Any help is appreaciated.

4

5 回答 5

44

这现在可以在 PowerShell / WMF 5.0 中实现

Copy-Item-FromSession-toSession参数。您可以使用其中之一并传入会话变量。

例如。

$cs = New-PSSession -ComputerName 169.254.44.14 -Credential (Get-Credential) -Name SQL
Copy-Item Northwind.* -Destination "C:\Program Files\Microsoft SQL Server\MSSQL10_50.SQL2008R2\MSSQL\DATA\" -ToSession $cs

在此处查看更多示例,或者您可以查看官方文档

于 2016-02-29T04:52:13.037 回答
21

如果它是一个小文件,您可以将文件的内容和文件名作为参数发送。

$f="the filename"
$c=Get-Content $f
invoke-command -session $s -script {param($filename,$contents) `
     set-content -path $filename -value $contents} -argumentlist $f,$c

如果文件太长而无法适应会话的任何限制,您可以将文件作为块读取,并使用类似的技术将它们一起附加到目标位置


PowerShell 5+ 对此具有内置支持,如David 的回答中所述。

于 2012-05-17T19:22:33.547 回答
4

不久前我遇到了同样的问题,并整理了一个概念验证,用于通过 PS Remoting 会话发送文件。您将在此处找到脚本:

https://gist.github.com/791112

#requires -version 2.0

[CmdletBinding()]
param (
    [Parameter(Mandatory=$true)]
    [string]
    $ComputerName,

    [Parameter(Mandatory=$true)]
    [string]
    $Path,

    [Parameter(Mandatory=$true)]
    [string]
    $Destination,

    [int]
    $TransferChunkSize = 0x10000
)

function Initialize-TempScript ($Path) {
    "<# DATA" | Set-Content -Path $Path 
}

function Complete-Chunk () {
@"
DATA #>
`$TransferPath = `$Env:TEMP | Join-Path -ChildPath '$TransferId'
`$InData = `$false
`$WriteStream = [IO.File]::OpenWrite(`$TransferPath)
try {
    `$WriteStream.Seek(0, 'End') | Out-Null
    `$MyInvocation.MyCommand.Definition -split "``n" | ForEach-Object {
        if (`$InData) {
            `$InData = -not `$_.StartsWith('DATA #>')
            if (`$InData) {
                `$WriteBuffer = [Convert]::FromBase64String(`$_)
                `$WriteStream.Write(`$WriteBuffer, 0, `$WriteBuffer.Length)
            }
        } else {
            `$InData = `$_.StartsWith('<# DATA')
        }
    }
} finally {
    `$WriteStream.Close()
}
"@
}

function Complete-FinalChunk ($Destination) {
@"
`$TransferPath | Move-Item -Destination '$Destination' -Force
"@
}

$ErrorActionPreference = 'Stop'
Set-StrictMode -Version Latest

$EncodingChunkSize = 57 * 100
if ($EncodingChunkSize % 57 -ne 0) {
    throw "EncodingChunkSize must be a multiple of 57"
}

$TransferId = [Guid]::NewGuid().ToString()


$Path = ($Path | Resolve-Path).ProviderPath
$ReadBuffer = New-Object -TypeName byte[] -ArgumentList $EncodingChunkSize

$TempPath = ([IO.Path]::GetTempFileName() | % { $_ | Move-Item -Destination "$_.ps1" -PassThru}).FullName
$Session = New-PSSession -ComputerName $ComputerName
$ReadStream = [IO.File]::OpenRead($Path)

$ChunkCount = 0
Initialize-TempScript -Path $TempPath 

try {
    do {
        $ReadCount = $ReadStream.Read($ReadBuffer, 0, $EncodingChunkSize)
        if ($ReadCount -gt 0) {
            [Convert]::ToBase64String($ReadBuffer, 0, $ReadCount, 'InsertLineBreaks') |
                Add-Content -Path $TempPath
        }
        $ChunkCount += $ReadCount
        if ($ChunkCount -ge $TransferChunkSize -or $ReadCount -eq 0) {
            # send
            Write-Verbose "Sending chunk $TransferIndex"
            Complete-Chunk | Add-Content -Path $TempPath
            if ($ReadCount -eq 0) {
                Complete-FinalChunk -Destination $Destination | Add-Content -Path $TempPath
                Write-Verbose "Sending final chunk"
            }
            Invoke-Command -Session $Session -FilePath $TempPath 

            # reset
            $ChunkCount = 0
            Initialize-TempScript -Path $TempPath 
        }
    } while ($ReadCount -gt 0)
} finally {
    if ($ReadStream) { $ReadStream.Close() }
    $Session | Remove-PSSession
    $TempPath | Remove-Item
}

一些小的更改将允许它接受一个会话作为参数,而不是开始一个新的。我发现在传输大文件时,目标计算机上的远程处理服务的内存消耗可能会变得非常大。我怀疑 PS Remoting 并不是真正设计用于这种方式的。

于 2012-05-18T01:00:51.873 回答
1
$data = Get-Content 'C:\file.exe' -Raw
Invoke-Command -ComputerName 'server' -ScriptBlock { $using:data | Set-Content -Path 'D:\filecopy.exe' }

实际上不知道最大文件大小限制是多少。

于 2016-08-19T09:30:33.123 回答
1

NET USE允许您为远程系统添加本地驱动器号,然后允许您在 PSSession 中使用驱动器号,甚至可以不使用 PSSession。如果您没有 Powershell v5.0,这很有帮助,即使您有,

您可以使用远程机器名称或其 IP 地址作为远程 UNC 路径的一部分,并且可以在同一行指定用户名和密码凭据:

    NET USE Z: \\192.168.1.50\ShareName /USER:192.168.1.50\UserName UserPassword  

另一个例子:

    NET USE Z: \\RemoteSystem\ShareName /USER:RemoteSystem\UserName UserPassword  

或者

    NET USE Z: \\RemoteSystem\ShareName /USER:Domain\UserName UserPassword  

如果您不在同一行提供用户凭据,系统将提示您输入它们:

>NET USE Z: \\192.168.1.50\ShareName
Enter the user name for '192.168.1.50': 192.168.1.50\UserName
Enter the password for 192.168.1.50: *****
The command completed successfully.

完成以下操作后,您可以删除驱动器号:

    NET USE Z: /delete

您可以使用 NET USE /? 获得完整的语法。

>net use /?
The syntax of this command is:

NET USE
[devicename | *] [\\computername\sharename[\volume] [password | *]]
        [/USER:[domainname\]username]
        [/USER:[dotted domain name\]username]
        [/USER:[username@dotted domain name]
        [/SMARTCARD]
        [/SAVECRED]
        [[/DELETE] | [/PERSISTENT:{YES | NO}]]

NET USE {devicename | *} [password | *] /HOME

NET USE [/PERSISTENT:{YES | NO}]  

NET是系统文件夹中的标准外部 .exe 命令,可以在 Powershell 中正常工作。

于 2017-04-11T12:36:12.433 回答