functionpowershellscriptblock

How to call a Scriptblock as a function parameter in Powershell


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

Solution

  • 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) {
        ...
    }