Search code examples
c#.netpowershelltuispectre.console

Difficult loading Spectre.Console .NET typed classes in Powershell


I'm trying to use the excellent Spectre.Console to create nice interactive prompts in powershell. So far I can get a simple Read-Host equivalent to work using the below:

Add-Type -AssemblyName ".\path\to\Spectre.Console.dll"
[Spectre.Console.AnsiConsole]::Ask("Test Ask","Test Default")

Which will produce:

Test Ask (Test Default): Test 123
Test 123

But when I try to access a "typed" class like so:

$select = [Spectre.Console.SelectionPrompt]

I get the error:

InvalidOperation: C:\path\to\proj\testing.ps1:7:11
Line |
   7 |  $select = [Spectre.Console.SelectionPrompt]
     |            ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
     | Unable to find type [Spectre.Console.SelectionPrompt].

Looking at the Spectre docs I can see that the class requires a return type , so I presume it's failing to find the class because I can't quite figure out how to provide it with a type in Posh. I've tried some variations such as adding ::New(),::Prompt() and prepending the object with [string], but it always fails to find the type.

I'm able to get the equivalent working in C# without issue, but if possible I'd like to avoid having to write a wrapper class just to get it going in Posh.

Name                           Value
----                           -----
PSVersion                      7.2.5
PSEdition                      Core
GitCommitId                    7.2.5
OS                             Microsoft Windows 10.0.19043
Platform                       Win32NT
PSCompatibleVersions           {1.0, 2.0, 3.0, 4.0…}
PSRemotingProtocolVersion      2.3
SerializationVersion           1.1.0.1
WSManStackVersion              3.0

Solution

  • Figured out about 5 minutes after I posted this.

    The proper term is Generics, and the way to access classes like this via powershell is as follows:

    [Spectre.Console.SelectionPrompt[string]]::New()
    

    Which successfully instantiates a new object with return type string.