我有一个文件,正在使用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
我得到错误
我希望这样做是在远程计算机上解析命令,以便它在远程计算机上创建一个新文件'C:\ Test \ 3.txt'并附加byte []。有什么想法可以实现吗?
最佳答案
我缺少将$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
关于powershell - 简单的ScriptBlock在本地工作,但不能在远程工作,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/38453957/