0
votes

How to call power shell script file by passing attributes in c#. I'm using below code to call ps1 file by passing inputs but getting error near invoke. error message:

System.Management.Automation.CommandNotFoundException: 'The term 'Get-Childitem C:\samplemm.ps1' 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.'

namespace SCOMWebAPI.Services
{
    public class MaintennceModeService
    {
        private static IEnumerable<PSObject> results;

        internal static string post(MaintenanceMode value)
        {
            // create Powershell runspace

            RunspaceConfiguration runspaceConfiguration = RunspaceConfiguration.Create();

            Runspace runspace = RunspaceFactory.CreateRunspace(runspaceConfiguration);
            runspace.Open();

            RunspaceInvoke scriptInvoker = new RunspaceInvoke(runspace);

            Pipeline pipeline = runspace.CreatePipeline();

            //Here's how you add a new script with arguments
            Command myCommand = new Command("Get-Childitem C:\\samplemm.ps1");
            CommandParameter testParam = new CommandParameter("mgmtserver", "NodeName");
            myCommand.Parameters.Add(testParam);

            pipeline.Commands.Add(myCommand);

            // Execute PowerShell script
            results = pipeline.Invoke();
            runspace.Close();
            // convert the script result into a single string

            StringBuilder stringBuilder = new StringBuilder();
            foreach (PSObject obj in results)
            {
              stringBuilder.AppendLine(obj.ToString());
            }

            return stringBuilder.ToString();
        }
    }
}
1

1 Answers

3
votes

When you type the command Get-ChildItem C:\\samplemm.ps1 into powershell, you are actually binding the text C:\\samplemm.ps1 to the default parameter Path.

The problem with your code is that you have included the first parameter as part of the command name. Simply separate it out.

Instead of

Command myCommand = new Command("Get-Childitem C:\\samplemm.ps1");

Separate out the parameter:

Command myCommand = new Command("Get-Childitem");
CommandParameter pathParameter = new CommandParameter("Path", "C:\\samplemm.ps1");
myCommand.Parameters.Add(pathParameter);