Greg Smith
Greg Smith

Reputation: 2469

Powershell Hashtable - Access outer object in nested script block

If I have a powershell hash object, thus:

$hash = @{
             Prop1 = "Hello";
             Prop2 = "Goodbye";
             ArbitraryScriptBlock = { Do-Things -SomeParameter ThisHashTable?}
         }

I want to pass the entire value of $hash to the Do-Things function, more or less analogous to passing this as an argument to a method in C#:

 var results = DoThings(this);

Is this possible?

Upvotes: 1

Views: 923

Answers (1)

Robert Westerlund
Robert Westerlund

Reputation: 4838

Yes, you can do this. Just pass in parameters to the script block and use the $args array to get the argument, like so:

$hash = @{
             Prop1 = "Hello";
             Prop2 = "Goodbye";
             ArbitraryScriptBlock = { Write-Host $args[0].Prop1 }
         }

$hash.ArbitraryScriptBlock.Invoke($hash)

I usually prefer specifying the parameters my functions and script blocks take as input, which would look similar to:

$hash = @{
             Prop1 = "Hello";
             Prop2 = "Goodbye";
             ArbitraryScriptBlock = { PARAM( $this ) Write-Host $this.Prop1 }
         }

$hash.ArbitraryScriptBlock.Invoke($hash)

Note: The $this variable name is not anything special and you can name it anything you want to.

You could also use the & call operator to execute the script block, which also lets you call the script block providing a nice familiar syntax:

$hash = @{
            Prop1 = "Hello";
            Prop2 = "Goodbye";
            ArbitraryScriptBlock = { PARAM( $ParamName ) Write-Host $ParamName.Prop1 }
        }

& $hash.ArbitraryScriptBlock $hash
# Or, perhaps even nicer:
& $hash.ArbitraryScriptBlock -ParamName $hash 

I suggest reading up on the help section about script blocks, which you can get by calling Get-Help about_Script_Blocks.

Upvotes: 3

Related Questions