PoshCode Archive  Artifact [be6c630088]

Artifact be6c630088e9029fb9f10fc01c60a7894adb6877874799b9f746bdf445397335:

  • File Invoke-ScriptBlockClosur.ps1 — part of check-in [88fa6ad47b] at 2018-06-10 13:06:40 on branch trunk — From Windows PowerShell Cookbook (O’Reilly) by Lee Holmes (user: Lee Holmes size: 1652)

# encoding: ascii
# api: powershell
# title: Invoke-ScriptBlockClosur
# description: From Windows PowerShell Cookbook (O’Reilly) by Lee Holmes
# version: 0.1
# type: script
# author: Lee Holmes
# license: CC0
# x-poshcode-id: 2186
# x-archived: 2016-03-19T00:35:24
# x-published: 2011-09-09T21:41:00
#
#
##############################################################################
##
## Invoke-ScriptBlockClosure
##
## From Windows PowerShell Cookbook (O'Reilly)
## by Lee Holmes (http://www.leeholmes.com/guide)
##
##############################################################################

<#

.SYNOPSIS

Demonstrates the GetNewClosure() method on a script block that pulls variables
in from the user's session (if they are defined.)

.EXAMPLE

PS >$name = "Hello There"
PS >Invoke-ScriptBlockClosure { $name }
Hello There
Hello World
Hello There

#>

param(
    ## The scriptblock to invoke
    [ScriptBlock] $ScriptBlock
)

Set-StrictMode -Version Latest

## Create a new script block that pulls variables
## from the user's scope (if defined.)
$closedScriptBlock = $scriptBlock.GetNewClosure()

## Invoke the script block normally. The contents of
## the $name variable will be from the user's session.
& $scriptBlock

## Define a new variable
$name = "Hello World"

## Invoke the script block normally. The contents of
## the $name variable will be "Hello World", now from
## our scope.
& $scriptBlock

## Invoke the "closed" script block. The contents of
## the $name variable will still be whatever was in the user's session
## (if it was defined.)
& $closedScriptBlock