简单的ScriptBlock在本地但不是远程工作

时间:2016-07-19 09:02:48

标签: powershell io powershell-v4.0

我有一个文件,我使用PowerShell 4.0从一台计算机转移到另一台计算机。我创建一个读缓冲区,将其转换为Base64String,然后打开一个新的PSSession。最后,我称之为代码:

#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 

我试过了

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

运行正常,创建文件并按预期编写byte []。我跑的时候

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

我收到错误

  

使用“2”参数调用“打开”的异常:“找不到部件   路径'C:\ Test \ 3.txt'。“

我期望这样做是在远程机器上解析命令,以便在远程机器上创建一个新文件'C:\ Test \ 3.txt'并附加byte []。我有什么想法可以实现这个目标吗?

2 个答案:

答案 0 :(得分:2)

我错过了将$stringBuffer传递给您的scriptblock的部分。但是,首先您可以使用大括号更容易地编写脚本块。然后,您可以使用$using:VARIABLENAME传递本地脚本变量:

$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

答案 1 :(得分:0)

您可以在本地将其写为函数,然后将该函数发送到远程计算机。

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