Skip to content

Instantly share code, notes, and snippets.

@Luiz-Monad
Last active March 8, 2020 00:40
Show Gist options
  • Save Luiz-Monad/7f798d355a1fb460b5e47d8339997b61 to your computer and use it in GitHub Desktop.
Save Luiz-Monad/7f798d355a1fb460b5e47d8339997b61 to your computer and use it in GitHub Desktop.
Powershell ScriptBlock serialization/deserialization
Function Serialize-Command
{
param(
[scriptblock]$Scriptblock
)
$rxp = '\$using:(?<var>\w+)'
$ssb = $Scriptblock.ToString()
$cb = {
$v = (Get-Variable -Name $args[0].Groups['var'] -ValueOnly)
$ser = [System.Management.Automation.PSSerializer]::Serialize($v)
"`$([System.Management.Automation.PSSerializer]::Deserialize('{0}'))" -f $ser
}
$sb = [RegEx]::Replace($ssb, $rxp, $cb, [System.Text.RegularExpressions.RegexOptions]::IgnoreCase)
$Serialized = [System.Management.Automation.PSSerializer]::Serialize($sb)
[System.Text.Encoding]::UTF8.GetBytes($Serialized)
}
Function Deserialize-Command
{
param(
[byte[]]$ScriptblockString
)
$Serialized = [System.Text.Encoding]::UTF8.GetString($ScriptblockString)
$sb = [System.Management.Automation.PSSerializer]::Deserialize($Serialized.ToString())
[Scriptblock]::Create($sb).GetNewClosure()
}
$a = "is this what you wanted?"
$b = Serialize-Command { "test $using:a" }
$a = "okay"
$c = Deserialize-Command $b
$a = "right"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment