gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 23:11:29 27 4
gpt4 key购买 nike

我有一个文件,我正在使用 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\3.txt'."



我期望这样做是解析远程机器上的命令,以便它在远程机器上创建一个新文件'C:\Test\3.txt'并附加字节[]。任何想法我怎么能做到这一点?

最佳答案

我错过了您通过 $stringBuffer 的部分到你的脚本 block 。但是,首先您可以使用大括号更轻松地编写脚本 block 。然后你可以使用 $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 - Simple ScriptBlock 在本地工作,但不能在远程工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38453957/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com