Home > database >  C# application with Powershell host
C# application with Powershell host

Time:12-21

The problem is about sending command to Powershell,

My C# application sends commands one by one in order to get right directory to execute some files but even I downloaded all the necessary packages application throws an error

An exception of type 'System.Management.Automation.CommandNotFoundException' in 'cd C:\\Users\\User1\\Documents\\pathToFileforExecute\\ ' is not recognized as the name of a cmdlet, function, script file, or operable program.

My NuGet Packages ; enter image description here

My code is like

ps.AddCommand("Set-ExecutionPolicy").AddParameter("ExecutionPolicy", "Unrestricted");
                ps.Invoke();
                ps.AddCommand("cd C:\\Users\\User1\\Documents\\pathToFileforExecute\\");
                ps.AddCommand("./executeTheFile");
                ps.AddCommand("pwd");
                Collection<System.Management.Automation.PSObject> results = ps.Invoke();

Please help me to solve problem I found this feed but it didn't work for me https://github.com/PowerShell/PowerShell/issues/8119

I tried deleting the System.Management.Automation because I read this package shouldn't use by itself.

CodePudding user response:

You are using AddCommand without the AddParameter option. The path is a parameter.

Try the following code:

ps.AddCommand("Set-Location").AddParameter("Path", C:\\Users\\User1\\Documents\\pathToFileforExecute\\);

Or you may use the AddScript method instead of AddCommand like in this post.

Note that the cd command is an alias for Set-Location in PowerShell.

  • Related