0

Using Cmdlet, (and/or PSCmdlet), I can create

[Cmdlet(VerbsCommunications.Read, "Blah", SupportsShouldProcess = true)]
public class BlahBlah : PSCmdlet
{
  /// ...
}

Then, in powershell, I can then call the command

import-module .\Blah.dll -Verbose
Read-Blah
...

And everything is fine.

But I would like to create a class rather than a function so I can get an object and then use it in powershell

Something like

import-module .\Blah.dll -Verbose
$myClass = New-Object Blah
$myClass.Read
$myClass.Save -File x.txt
$myClass.BlahBlah
...

Can the above be done in C#? If so, how?

1 Answer 1

1

If you want to import a class from a .NET assembly, you need to use Add-Type, and not Import-Module:

Add-Type -Path .\Blah.dll

At this point, all public classes defined in your assembly will be available from PowerShell.

Sign up to request clarification or add additional context in comments.

5 Comments

Ok, thanks, but how to I create the class itself? The example I gave only creates a function, not a class.
@SimonGoodman: I'm not sure I understand what you're asking... when you talk about a "function" you mean your BlahBlah CmdLet class, right? If you want to create a class in C#, then you just need to declare a public class that does not inherit from CmdLet. Does this answer your question?
What I mean is when I create a function [Cmdlet(VerbsCommunications.Read, "Blah"... I will then be able to use it in powershell as Read-Blah but now I would like a class to be available, as in $myClass = New-Object Blah or are you saying that it will be available to powershell as long as it is public?
@SimonGoodman: if you import the dll with Add-Type -Path, all the public types will be available from PowerShell, yes.
Well I feel rather silly, so straightforward... I thought I needed to derive from some other cmdlet or something.

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.