Click here to Skip to main content
15,881,559 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi,

I am Trying to Run Powershell from C# with the help of System.Diagnostics.Process class.
I tries passing commands to the powershell as Arguments but Nothing happens here. Powershell starts in the Task Manager but it does not accepts the commands.
Plz tell me changes is required here to make powershell accept these commands.

CODE:
C#
private static void copy(string source, string dest)
        {

            System.Diagnostics.Process process = new System.Diagnostics.Process();
            System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
            startInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
            startInfo.FileName = "powershell.exe";

            //dest = @"D$\";
            dest = dest.Remove(1, 1).Insert(1, "$");
            //dest = dest + "\\";
            string str = dest.Remove(dest.LastIndexOf("$"));
            str = str.Insert(1, "$");
            string server = "10.0.4.41";
            string cmd1 = "net use \\\\"+server+"\\"+str+" \"support@123\" /USER:ibmairtelafrica\\l2support";
            //startInfo.Arguments = cmd1;
            dest = dest + "\\";
            string cmd2 = "if(!(Test-Path -path \"\\\\" + server + "\\" + dest + "\")) {New-Item \"\\\\" + server + "\\" + dest + "\" -Type Directory}";
            //startInfo.Arguments = cmd2;
            string cmd3 = "copy-item -path \"" + source + "\" \"\\\\" + server + "\\" + dest + "\" -Recurse -Force";
            //startInfo.Arguments = cmd3;
            string c = cmd1 + ";" + cmd2 + ";" + cmd3;
            startInfo.Arguments = c;
            //string ex = "exit";
            //startInfo.Arguments = ex;
            
            startInfo.CreateNoWindow = true;
            startInfo.RedirectStandardInput = true;
            startInfo.RedirectStandardOutput = true;
            startInfo.UseShellExecute = false;
            process.StartInfo = startInfo;
            process.Start();
            
            //process.StandardInput.WriteLine(cmd3);
            

        }


Thanks & Regards
Rammohan
Posted

1 solution

You have a syntax error in the commands that you are sending to PowerShell.
Change your code a bit so you can see the error message from PowerShell.
In Visual Studio Debug mode, capture the value of "c" just before you assign it to startinfo.arguments and use it in an interactive PowerShell window to determine the exact cause of your syntax error.

Here is how I revised your code to see the PowerShell error:
...
            startInfo.RedirectStandardOutput = true;
            startInfo.UseShellExecute = false;
            process.StartInfo = startInfo;
            process.Start();
            StreamReader sr = process.StandardOutput;
            while (! sr.EndOfStream) 
                {
                    Console.WriteLine(sr.ReadLine());
                };

Here is the PowerShell error:
+ ... \\10.0.4.41\B$B" -Recurse -Force
+                    ~~~~~~~~~~~~~~~~~
The string is missing the terminator: ".
    + CategoryInfo          : ParserError: (:) [], ParentContainsErrorRecordException
    + FullyQualifiedErrorId : MissingEndParenthesisInExpression


Added to solution
I think the problem may be related to the fact that C# uses \ character as an escape character so you end up putting in all these extra \ characters. When you copy the "c" variable to the ClipBoard and try to use that in PowerShell, PowerShell does not use \ as an escape character.

Therefore, I wonder, for debugging, if it would be a good idea to do the following:
1. In PowerShell develop a script that works 100% of the time.
2. Use that script as the basis to develop C# code to generate the same script putting in the extra \ characters where needed.
---- The following is for developing and debugging - It will not be part of your final program --
3. Have your C# program write the PowerShell commands to a text file (.txt)
4. Open the .txt file in NotePad (interactively) and copy the PowerShell commands to the ClipBoard
5. Open PowerShell (interactively) and paste the commands into PowerShell to test them.
6. Repeat steps 3-5 until you have C# code that generates a set of PowerShell commands that work correctly.
---- When the C# generated commands work correctly ----
7. Remove the creation of the .txt file from your C# program.
 
Share this answer
 
v2
Comments
rammohan004 1-Apr-13 0:51am    
Hi Mike,

Thanks for the Reply..

I tried as you said..I Kept a breakpoint in string 'c' and tried to execute that string directly from the powershell and command executed successfully.


string cmd1 = "net use \\\\"+server+"\\"+str+" \"support@123\" /USER:ibmairtelafrica\\l2support";
dest = dest + "\\\\";

string cmd2 = "if(!(Test-Path -path \"\\\\" + server + "\\" + dest + "\")) {New-Item \"\\\\" + server + "\\" + dest + "\" -Type Directory}";

string cmd3 = "copy-item -path \"" + source + "\" \"\\\\" + server + "\\" + dest + "\" -Recurse -Force";

string c = cmd1 + ";" + cmd2 + ";" + cmd3;
startInfo.Arguments = c;



It Executes Successfully from the Powershell..
But from visual stdio it was showing the error as you indicated..
So, I did some changes in the s

tring 'dest' to solve that error from the Visual studio.
i.e.

string cmd1 = "net use \\\\"+server+"\\"+str+" \"support@123\" /USER:ibmairtelafrica\\l2support";
dest = dest + "\\\\";



This time Visual Stdio Executes it perfectly..But when i tried copying the files which contains white spaces it doesnot worked..

Again I did inserted all the path inside ("") but still it didn't worked for me..
<pre lang="c#">
string cmd2 = "if(!(Test-Path -path \"\"\\\\" + server + "\\" + dest + "\"\")) {New-Item \"\"\\\\" + server + "\\" + dest + "\"\" -Type Directory}";

string cmd3 = "copy-item -path \"\"" + source + "\"\" \"\"\\\\" + server + "\\" + dest + "\"\" -Recurse -Force";

string c = cmd1 + ";" + cmd2 + ";" + cmd3;
startInfo.Arguments = c;


Plz tell me what to do here..

Thanks and Regards..
Mike Meinz 1-Apr-13 7:29am    
I think the problem may be related to the fact that C# uses \ character as an escape character so you end up putting in all these extra \ characters. When you copy the "c" variable to the ClipBoard and try to use that in PowerShell, PowerShell does not use \ as an escape character.

Therefore, I wonder, for debugging, if it would be a good idea to do the following:
1. In PowerShell develop a script that works 100% of the time.
2. Use that script as the basis to develop C# code to generate the same script putting in the extra \ characters where needed.
---- The following is for developing and debugging - It will not be part of your final program --
3. Have your C# program write the PowerShell commands to a text file (.txt)
4. Open the .txt file in NotePad (interactively) and copy the PowerShell commands to the ClipBoard
5. Open PowerShell (interactively) and paste the commands into PowerShell to test them.
6. Repeat steps 3-5 until you have C# code that generates a set of PowerShell commands that work correctly.
---- When the C# generated commands work correctly ----
7. Remove the creation of the .txt file from your C# program.
rammohan004 2-Apr-13 6:32am    
Thanks for the Help Mike..
It really Worked for me..
Mike Meinz 2-Apr-13 6:37am    
That is good news.
Perhaps you could give Solution 1 a 5 rating and accept it as the answer.
Thank you.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900