1

I want to create a powershell function and use it from inside the C#

using System;
using System.Management.Automation;
using System.Text;
namespace PowerShell_eg
{
    public class Program
    {
        public static void Main(String[] args)
        {
            var psFunction = @" function Get-Hostname { hostname } ";

            RunspaceConfiguration runspaceConfiguration = RunspaceConfiguration.Create();
            Runspace runspace = RunspaceFactory.CreateRunspace(runspaceConfiguration);
            runspace.Open();
            RunspaceInvoke scriptInvoker = new RunspaceInvoke(runspace);    
            Pipeline pipeline = runspace.CreatePipeline();

            ??// HOW TO Add Get-Hostname & INVOKE IT ??

            pipeline.Commands.AddScript(psFunction);
            pipeline.Commands.Add("Get-Hostname");
            var results = pipeline.Invoke();
            foreach (var obj in results.Where(o => o != null))
            {
                Console.WriteLine("\t" + obj);
            }
        }
    }
}

Currently I get CommandNotFound exception @ Invoke. The term 'Get-Hostname' is not recognized as the name of a cmdlet, function, script file, or operable program.

Please advice how to correctly do this!

Also it will be ideal if I can add multiple functions and cont. to use them over the life of the powershell session without having to add them again and again.

1 Answer 1

3

This C# code seems to work fine for me. Just add a reference to the System.Management.Automation .NET assembly.

using System;
using System.Management.Automation;

namespace PowerShellTest02
{
    class Program
    {
        static void Main(string[] args)
        {
            string func = @"function Test { Write-Host 'hello' };";
            PowerShell ps = PowerShell.Create();
            ps.AddScript(func);
            ps.Invoke();
            ps.AddCommand("Test");
            ps.Invoke();
            Console.WriteLine("Successfully executed function");
            Console.ReadLine();
        }
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

It works, but when I provide string func='ps1 file path it shows error that the term Test is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again

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.