Simple ScriptBlock 在本地工作但不能在远程工作

Simple ScriptBlock works locally but not remotely

我有一个文件,我正在使用 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

我收到错误

Exception calling "Open" with "2" argument(s): "Could not find a part of the path 'C:\Test.txt'."

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

我遗漏了将 $stringBuffer 传递给脚本块的部分。但是,首先您可以使用大括号更轻松地编写脚本块。然后你可以使用 $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

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

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