Preventing Direct Function Calls

by Jun 26, 2013

If you must make sure that a function within your script is inaccessible from outside calls, you can use this trick. Save this code as a script file, then run it:

$scriptPath = $MyInvocation.MyCommand.Definition

function Test
{

    if ($MyInvocation.ScriptName -ne $script:scriptPath)
    {
        Write-Host "Direct call not allowed" -ForegroundColor Red
    }

    "OK"

}

Test

The function "Test" works just fine when called from within your script. However, when you try and call the function interactively or from within another script, it refuses to run with a red message.

Typically, when you run scripts non-dot-sourced, all functions within a script remain invisible for the outside caller, so this trick isn't necessary. However, if the user runs the script dot-sourced (by calling it with a dot) or inside the ISE editor, any function defined by the script can be called.

The code above determines the current script path (which is why the example only works once you save it as a script) and stores this in a script-global variable. The function then checks whether the caller was the same script. If not, it refuses to run.

Twitter This Tip! ReTweet this Tip!