0

I would like to have a function to run different ScriptBlocks. So, I need to use my Scriptblock as the parameter of the function. It does not work.

For example. This function returns the ScriptBlock as a string.

function Run_Scriptblock($SB) {
    return $SB
}

These are the outputs from my tries:

# 1st try
Run_Scriptblock {systeminfo}

>> systeminfo


# 2nd try
Run_Scriptblock systeminfo

>> systeminfo


# 3rd try
Run_Scriptblock [scriptblock]systeminfo

>> [scriptblock]systeminfo


# 4th try
$Command = [scriptblock]{systeminfo}
Run_Scriptblock $Command

>> [scriptblock]systeminfo


# 5th try
[scriptblock]$Command = {systeminfo}
Run_Scriptblock $Command

>> systeminfo

1 Answer 1

4

If you want a function to run a scriptblock, you need to actually invoke or call that scriptblock, i.e.

function Run_Scriptblock($SB) {
    $SB.Invoke()
}

or

function Run_Scriptblock($SB) {
    & $SB
}

Otherwise the function will just return the scriptblock definition in string form. The return keyword is not needed, since PowerShell functions return all non-captured output by default.

The function would be called like this:

Run_Scriptblock {systeminfo}

As a side note, I would recommend you consider naming your function following PowerShell conventions (<Verb>-<Noun> with an approved verb), e.g.

function Invoke-Scriptblock($SB) {
    ...
}
Sign up to request clarification or add additional context in comments.

2 Comments

I'd also add the cmdlet 'invoke-expression' to this list too.
@M2065 I wouldn't, and neither should you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.