0

I want to write cmdlet in c# just inside powershell script, so that I don't need to compile it myself, and also can leverage the WriteObject()/WriteError() functions, but it doesn't work, anyone know how to do this?

$code = @"
    using System;
    using System.Management.Automation;

    [Cmdlet("Write", "Hello")]
    public class WriteHello : PSCmdlet
    {
        [Parameter(Position =0)]
        public  String Msg  { get; set; }

        protected override void ProcessRecord()
        {
            //WriteObject("Hello: " + Msg);
            Console.WriteLine("Hello: " + Msg);
        }
    }
"@

    Add-Type $code

    $cmdlet = [WriteHello]::new()
    # Error when invoke().
    $cmdlet.Invoke() 

1 Answer 1

1

First, please share errors messages:

An error occurred while enumerating through a collection: Cmdlets derived from PSCmdlet cannot be invoked directly.

It's obvious.


Solution 1

Use Cmdlet instead of PSCmdlet if that satisfies your needs.

Solution 2

$code = ...
Add-Type $code
$WriteHello = [System.Management.Automation.CmdletInfo]::new("Write-Hello", [WriteHello])
& $WriteHello -msg "abcd"

I recommend to compile the source code anyway. Add-Type is basically a wrapper of pre-installed "cscript.exe". It create a CS file in the Temp directory and compile it.


Edit

Import-Module from a source code.

Add-Type $code -PassThru | % { Import-Module $_.Assembly }
Sign up to request clarification or add additional context in comments.

2 Comments

Great, thanks, I use Add-Type to compile it to avoid manually compile after each time I modified it. Do you know if it is possible to register the Write-Hello cmdlet, so that I can directly invoke it by: Write-Hello -msg abcd
@xinglong I updated the answer. Please try after Edit.

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.