Skip to content

Instantly share code, notes, and snippets.

@briantist
Last active December 12, 2019 01:45
Show Gist options
  • Save briantist/b99961494e41cbc95689 to your computer and use it in GitHub Desktop.
Save briantist/b99961494e41cbc95689 to your computer and use it in GitHub Desktop.
Manual substitution of $Using variables with serialized versions for embedding in DSC Script resources
function Replace-Using {
[CmdletBinding(DefaultParameterSetName = 'AsString')]
[OutputType([String], ParameterSetName = 'AsString')]
[OutputType([ScriptBlock], ParameterSetName = 'AsScriptBlock')]
param(
[Parameter(
Mandatory,
ValueFromPipeline
)]
[String]
$Code ,
[Parameter(
Mandatory,
ParameterSetName = 'AsScriptBlock'
)]
[Switch]
$AsScriptBlock
)
Process {
$cb = {
$m = $args[0]
$ser = [System.Management.Automation.PSSerializer]::Serialize((Get-Variable -Name $m.Groups['var'] -ValueOnly))
"`$([System.Management.Automation.PSSerializer]::Deserialize('{0}'))" -f $ser
}
$newCode = [RegEx]::Replace($code, '\$Using:(?<var>\w+)', $cb, [System.Text.RegularExpressions.RegexOptions]::IgnoreCase)
if ($AsScriptBlock.IsPresent) {
[ScriptBlock]::Create($newCode)
} else {
$newCode
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment