Last active
December 12, 2019 01:45
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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