PowerShell: Passing External Data into Register-ScriptFeedbackProvider

Created August 6, 2024

In my latest module, PSTerminalBoom, I encountered a challenge: how to pass external data into the Register-ScriptFeedbackProvider script block. Unfortunately, $using: didn't work in this context due to the implementation of the function itself.

So, how can we pass in external data? A neat trick is to use Add-Type to create a helper static class. This class will be accessible in any spawned runspace, allowing us to pass the necessary data.

Example 1: Passing a File Path

Here's an example of how to pass a file path to a GIF:

$GifPath = $PSScriptRoot + '\Boom.gif'
Add-Type -TypeDefinition @"
public static class PSTBHelperClass
{
    private static string _gifPath = "Initial Path";

    public static string GifPath
    {
        get { return _gifPath; }
        set { _gifPath = value; }
    }
}
"@

[PSTBHelperClass]::GifPath = $GifPath

Register-ScriptFeedbackProvider -Name PassingFromOuside -Trigger Error -ScriptBlock {
 Write-Host [PSTBHelperClass]::GifPath 
}

With this method, you can ensure that the file path is available in the script block.

Example 2: Passing a Function

You can also pass a function using a similar approach:

$FunctionCode = 'return "Hello World"'
Add-Type -TypeDefinition @"
public static class PSTBHelperClass
{
    private static string _FunctionCode = "Function Code";

    public static string FunctionCode
    {
        get { return _FunctionCode; }
        set { _FunctionCode = value; }
    }
}
"@

[PSTBHelperClass]::FunctionCode = $FunctionCode

Register-ScriptFeedbackProvider -Name ExecuteFunction -Trigger Error -ScriptBlock {
 ${function:Write-HelloWorld} = [ScriptBlock]::Create([PSTBHelperClass]::FunctionCode)
 Write-HelloWorld
}

In this example, a function is passed into the script block, which can then be executed as needed.

Have You Tried ScriptFeedBackProvider?

Have you used Justin Grote's module: ScriptFeedBackProvider? It's a powerful tool that can enhance your PowerShell scripts by providing feedback mechanisms.

If you have any thoughts or feedback on this topic, feel free to share them with me on Twitter at Christian Ritter.

Best regards,

Christian