I have a powershell script, say: function2.ps1 with:
function try2
{
return "Hello"
}
and then in c#, I have:
RunspaceConfiguration rsc = RunspaceConfiguration.Create();
Runspace rs = RunspaceFactory.CreateRunspace(rsc);
rs.Open();
RunspaceInvoke si = new RunspaceInvoke(rs);
PowerShell ps = PowerShell.Create();
ps.Commands.AddScript(". .\\function2.ps1");
ps.Invoke();
ps.AddCommand("try2");
ps.Invoke();
It gives out a System.Managment.Automation.CommandNotFoundException saying that try2 is not recognized as the name of a cmdlet, function, script file, blah blah blah.
This is really tricky, what do I miss? :)
UPDATE:
function.ps1 is located: c:\function.ps1.
The current approach is:
ps.Commands.AddScript(@"cd C:\; . .\function.ps1;try2");
ps.Invoke();
but still failing, and even more interesting:
ps.Commands.AddScript(@"cd C:\; . .\function222222222222222222.ps1;try2");
ps.Invoke();
although I am 100% sure the function22222222222222222222.ps1 DOES NOT EXIST but no error will be given. For sure there is something wrong with giving the file path...
[UPDATE]
It turned out that it is because of some runtime errors in the referncing assembly in the powershell file: This assembly is built by a runtime newer than the currently loaded runtime and cannot be loaded.
After changing the target framework from 4.0 to 3.5, I find that the hello is printed! So the error is not about calling the script but is about the script itself. Sorry for confusion and thank you everyone!