当前位置: 动力学知识库 > 问答 > 编程问答 >

powershell - Simple ScriptBlock works locally but not remotely

问题描述:

I have a file which I am transfering from one computer to another using PowerShell 4.0. I create a read buffer, turn that into a Base64String then open a new PSSession. Finally, I call this code:

#Open a file stream to destination path in remote session and write buffer to file

#First save string buffer to variable so FromBase64String() parses correctly in ScriptBlock

$remoteCommand =

"#First save string buffer to variable so FromBase64String() parses correctly below

`$writeString = `"$stringBuffer`"

`$writeBuffer = [Convert]::FromBase64String(`"`$writeString`")

`$writeStream = [IO.File]::Open(`"$destPath`", `"Append`")

`$writeStream.Write(`$writeBuffer, 0, `$writeBuffer.Length)

`$WriteStream.Close()

"

Invoke-Command -ScriptBlock{ Invoke-Expression $args[0] } -ArgumentList $remoteCommand -Session $remoteSession

I have tried running

Invoke-Command -ScriptBlock{ Invoke-Expression $args[0] } -ArgumentList $remoteCommand

Which runs fine, creating a file and writing the byte[] as expected. When I run

Invoke-Command -ScriptBlock{ Invoke-Expression $args[0] } -ArgumentList $remoteCommand -Session $remoteSession

I get the error

Exception calling "Open" with "2" argument(s): "Could not find a part

of the path 'C:\Test\3.txt'."

What I expected this to do was parse the command on the remote machine, so that it creates a new file 'C:\Test\3.txt' on the remote machine and appends the byte[]. Any ideas how I could acheive this?

网友答案:

Im missing the part where you pass the $stringBuffer to your scriptblock. However, first you can write a scriptblock much more easy using curly brackets. Then you could use $using:VARIABLENAME to pass a local script variable:

$remoteCommand = {
    #First save string buffer to variable so FromBase64String() parses correctly below
    $writeString = $using:stringBuffer
    $writeBuffer = [Convert]::FromBase64String($writeString)
    $writeStream = [IO.File]::Open($destPath, "Append")
    $writeStream.Write($writeBuffer, 0, $writeBuffer.Length)
    $WriteStream.Close()
}

Invoke-Command -ScriptBlock $remoteCommand -Session $remoteSession
网友答案:

You could write it as a function locally and then send the function to the remote computer.

function remoteCommand 
   {
    #First save string buffer to variable so FromBase64String() parses correctly       below
    $writeString = $using:stringBuffer
    $writeBuffer = [Convert]::FromBase64String($writeString)
    $writeStream = [IO.File]::Open($destPath, "Append")
    $writeStream.Write($writeBuffer, 0, $writeBuffer.Length)
    $WriteStream.Close()
   }

Invoke-Command -ScriptBlock ${function:remoteCommand} -Session $remoteSession
分享给朋友:
您可能感兴趣的文章:
随机阅读: