Dot-sourcing powershell script in C # not working
I have a powershell script, say: function2.ps1 with:
function try2
{
return "Hello"
}
and then in C #, I:
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 throws System.Managment.Automation.CommandNotFoundException saying try2 is not recognized as the name of a cmdlet, function, script file, blah blah blah.
Is it really hard, what am I missing? :)
UPDATE:
function.ps1 is located: c: \ function.ps1.
Current approach:
ps.Commands.AddScript(@"cd C:\; . .\function.ps1;try2");
ps.Invoke();
but still doesn't work, and even more interesting:
ps.Commands.AddScript(@"cd C:\; . .\function222222222222222222.ps1;try2");
ps.Invoke();
although I am 100% sure that the function 22222222222222222222.ps1 DOESN'T EXIST, there will be no error. Of course there is something wrong with providing the file path ...
[UPDATE]
It turned out to be due to some errors during link building in the powershell file: This assembly is built using a runtime newer than the currently loaded runtime and cannot be loaded.
After changing the target structure from 4.0 to 3.5, I found myself to be welcome! So the error is not in the call to the script, but in the script itself. Sorry for the confusion and thank you all!
source to share
I think you need to provide the full path to function2.ps1
. ". \ function2.ps1" will only look for a script in the current directory that is installed regardless of the starting working directory of the C # process, unless you change it somewhere in your C # code. You can also change it in a script like:
ps.Commands.AddScript(@"cd <path>; . .\function2.ps1; try2");
source to share
One method (very close to yours) of running .ps1 scripts from C # can be found at:
http://www.codeproject.com/Articles/18229/How-to-run-PowerShell-scripts-from-C
You seem to be missing a few Pipeline commands to get the script to run.
eg:
Pipeline pipeline = runspace.CreatePipeline();
pipeline.Commands.AddScript(scriptText);
pipeline.Commands.Add("Out-String");
// execute the script
Collection<psobject /> results = pipeline.Invoke();
If you cannot find the System.Management.Automation dll, you might need to download a newer version of the Windows SDK , if not, you can find it at: C: \ Program Files (x86) \ Reference Assemblies \ Microsoft \ WindowsPowerShell \ v1.0 \
from: Link to system.management.automation.dll in Visual Studio
source to share