Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- ## Scriptblock
- $Data = 42
- $Computername = $env:COMPUTERNAME
- $ScriptBlock = {
- [pscustomobject]@{
- Output = (4 + $Using:Data * 2)
- Computername = $Using:Computername
- }
- }
- ## Let's be quick and dirty and do a search and replace on the scriptblock
- $usingVariables = $ScriptBlock.ast.FindAll({
- $args[0] -is [System.Management.Automation.Language.UsingExpressionAst]
- },$True)
- $List = New-Object 'System.Collections.Generic.List`1[System.Management.Automation.Language.VariableExpressionAst]'
- $Params = New-Object System.Collections.ArrayList
- If ($UsingVariables) {
- ForEach ($Ast in $UsingVariables) {
- [void]$list.Add($Ast.SubExpression)
- }
- [void]$Params.AddRange(($UsingVariableData.NewName | Select -Unique))
- $NewParams = $Params -join ', '
- $Tuple=[Tuple]::Create($list,$NewParams)
- $bindingFlags = [Reflection.BindingFlags]"Default,NonPublic,Instance"
- $GetWithInputHandlingForInvokeCommandImpl = ($ScriptBlock.ast.gettype().GetMethod('GetWithInputHandlingForInvokeCommandImpl',$bindingFlags))
- $StringScriptBlock = $GetWithInputHandlingForInvokeCommandImpl.Invoke($ScriptBlock.ast,@($Tuple))
- $ScriptBlock = [scriptblock]::Create($StringScriptBlock)
- }
- $serializedVariables = foreach($variable in $list) {
- [pscustomobject]@{
- Name = '__using_' + $variable.VariablePath.UserPath
- SerializedValue = [System.Management.Automation.PSSerializer]::Serialize(
- (Get-Variable -Name $variable.VariablePath.UserPath).Value
- )
- }
- }
- foreach($serializedVariable in $serializedVariables) {
- Set-Variable -Name $serializedVariable.Name -Value (
- [System.Management.Automation.PSSerializer]::Deserialize($serializedVariable.SerializedValue)
- )
- }
- $ScriptBlock
- . $ScriptBlock
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement