Neptune443

My $using implementation

May 8th, 2015
356
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. ## Scriptblock
  2. $Data = 42
  3. $Computername = $env:COMPUTERNAME
  4. $ScriptBlock = {
  5.     [pscustomobject]@{
  6.         Output = (4 + $Using:Data * 2)
  7.         Computername = $Using:Computername
  8.     }
  9. }
  10.  
  11. ## Let's be quick and dirty and do a search and replace on the scriptblock
  12. $usingVariables = $ScriptBlock.ast.FindAll({
  13.     $args[0] -is [System.Management.Automation.Language.UsingExpressionAst]
  14. },$True)
  15.  
  16. $List = New-Object 'System.Collections.Generic.List`1[System.Management.Automation.Language.VariableExpressionAst]'
  17. $Params = New-Object System.Collections.ArrayList
  18.  
  19. If ($UsingVariables) {        
  20.     ForEach ($Ast in $UsingVariables) {
  21.         [void]$list.Add($Ast.SubExpression)
  22.     }
  23.     [void]$Params.AddRange(($UsingVariableData.NewName | Select -Unique))
  24.     $NewParams = $Params -join ', '
  25.     $Tuple=[Tuple]::Create($list,$NewParams)
  26.  
  27.     $bindingFlags = [Reflection.BindingFlags]"Default,NonPublic,Instance"
  28.     $GetWithInputHandlingForInvokeCommandImpl = ($ScriptBlock.ast.gettype().GetMethod('GetWithInputHandlingForInvokeCommandImpl',$bindingFlags))
  29.     $StringScriptBlock = $GetWithInputHandlingForInvokeCommandImpl.Invoke($ScriptBlock.ast,@($Tuple))
  30.     $ScriptBlock = [scriptblock]::Create($StringScriptBlock)
  31. }
  32.  
  33. $serializedVariables = foreach($variable in $list) {
  34.     [pscustomobject]@{
  35.         Name = '__using_' + $variable.VariablePath.UserPath
  36.         SerializedValue = [System.Management.Automation.PSSerializer]::Serialize(
  37.             (Get-Variable -Name $variable.VariablePath.UserPath).Value
  38.         )
  39.     }
  40. }
  41.  
  42. foreach($serializedVariable in $serializedVariables) {
  43.     Set-Variable -Name $serializedVariable.Name -Value (
  44.         [System.Management.Automation.PSSerializer]::Deserialize($serializedVariable.SerializedValue)
  45.     )
  46. }
  47. $ScriptBlock
  48. . $ScriptBlock
RAW Paste Data