Sam
Sam

Reputation: 1479

Invoke Raw Command in Host Powershell from PSCmdlet class (C#)

I am playing with class PSCmdlet.

Is there a way I can invoke a command in host powershell that executed my command?

e.g:

I would like to do a function to set some alias.

public void myAliases() {
// Invoke Set-Alias in host ?
}

I tried to instance Powershell.Create() and AddCommand() but didn't work for me.

Thanks in advance!

Upvotes: 0

Views: 293

Answers (1)

Jawad
Jawad

Reputation: 11364

You can write your class libraries in c# and extend PSCmdlet to create methods that can be consumed directly in powershell.

To do that, you will need a method with declaration of how it will be called

    [Cmdlet("Lookup", "Aliases")]
    public class LookupAliases: PSCmdlet 
    {

        [Parameter(Mandatory = true,
            ValueFromPipeline = false,
            ValueFromPipelineByPropertyName = false,
            ParameterSetName = "1",
            HelpMessage = "Indicates the help message")]
        public string FirstArgument{ get; set; }

        protected override void ProcessRecord()
        {
            // write your process here.
            base.ProcessRecord();
        }
    }

In powershell, you will need to import this dll that you created above (Compile Solution) and run in powershell

Lookup-Aliases -FirstArugment "value"

If you are looking to run powershell commands inside c#,

    Runspace runSpace = RunspaceFactory.CreateRunspace();
    runSpace.Open();

    Pipeline pipeline = runSpace.CreatePipeline();

    string script = "your powershell script here";
    pipeline.Commands.AddScript(script);

    Collection<PSObject> output = pipeline.Invoke();

Upvotes: 1

Related Questions