0
votes

I'm trying to call PowerShell function through c# code.

**#This is sample PowerShell function**

function Add-num {

param($int1,$int2)

Write-Host ($int1 + $int2)

}


**#This is my c# code**

 class Program
    {

        static void Main(string[] args)
        {
            String file = @"E:\powershell\Untitled3.ps1";

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

            using (PowerShell PowerShellInstance = PowerShell.Create())
            {
                PowerShellInstance.AddScript(file);
                PowerShellInstance.AddCommand("Add-num").AddParameters(new Dictionary<string, string>
                {
                    {"int1","6" },
                    {"int2","7" }
                });






               // Collection<PSObject> PSOutput = PowerShellInstance.Invoke();

                foreach (PSObject outputItem in PowerShellInstance.Invoke())
                {
                    Console.WriteLine(outputItem.BaseObject);
                }
                runspace.Close();
        }
    }
}

Error: An unhandled exception of type 'System.Management.Automation.CommandNotFoundException' occurred in System.Management.Automation.dll

Additional information: The term 'Add-num' 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.

The above error is thrown when I execute this code. But when I run from PowerShell code works fine. I've checked the file path and file name everything is fine can anyone help me on this. The error is pointing at Invoke.

1
I was able to execute any other scripts but not this script. For suppose I have $dateInput = 10 $dateInput if($dateInput -eq $null) { Write-Host "null" } else { Write-Host "not null" } This script in another file and executed successfully. - user3278314
But when I run from PowerShell code works fine. Are you saying that this command work fine in PowerShell: .{E:\powershell\Untitled3.ps1} | Add-num -int1 '6' -int2 '7'? - user4003407

1 Answers

0
votes

I've done the following before:

string command = @"C:\temp.ps1";
var fileName = "powershell";
var args = $"-ExecutionPolicy unrestricted . '{command}'";

var process = CreateProcess(fileName, args);
process.Start();