Script blocks

A script block is characterized by curly braces and can accept parameters. It is the building block of functions, DSC configurations, Pester tests, and much more. Take the following code sample to see how script blocks can be used:

# A script block without parameters
{
"Something is happening here
}

# Executing a script block
({
"Something is happening here
}).Invoke()
# Or use the ampersand
& {
"Something is happening here
}

The objects returned in your script block are returned to the output stream, and they can be processed or stored in a variable like it is done in the next code sample:

# With parameters
$scriptBlockArgs = {
# Built-in - not recommended
"$($args[0]) is happening here"
}

# Better
$scriptBlockParam = {
param
(
[string]
$TheThing
)
# Built-in - not recommended
"$TheThing is happening here"
}

$scriptBlockArgs.Invoke('Something')

# Named parameters are possible
$scriptBlockParam.Invoke('Something')
& $scriptBlockParam -TheThing SomeThing
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset