0

Script powershell inside C# code

Hellooo, In my c# code, i put some powershell script. This script powershell is to write in a txt file the computer name and the username. It seams to me that the symbole $ is not recognize. Can you help me please. Here is my code startInfo.Arguments = " $ordi = $env: COMPUTERNAME " + " $utilisateur = $env: USERNAME " + "------------MON ORDI-------------`r`n" + "'Nom de l''ordinateur : $ordi`r`n" + "'Nom de l''utilisateur :$utilisateur >> C:/Users/Data/Documents/Batch/infoOrdi.txt";

4th Jun 2017, 9:56 PM
Attitude
Attitude - avatar
6 Réponses
+ 1
I agree with jay and MrProgrammer. That using C# to let powershell create a file is to difficult (cumbersome/devious excuse my english) . But you are probably want to do something else and want to get some experience this way. if you want to write a file. Do it using filestream and give the file extension .ps1 . In this way you have a true powershell file and better code in c#. The way you do it now is easy creating bugs. if you think the $-sign is the problem than use the @-character. (It means that special chars don't need to be escaped, since you informed the compiler to expect special characters, https://stackoverflow.com/questions/16635176/what-is-a-verbatim-string) like this startInfo.FileName = "cmd.exe"; startInfo.Arguments = @"/C echo $hLLO >> C:\Temp\file2.txt"; (sorry used cmd.exe to test is) also notice that in my path I use backslashes
5th Jun 2017, 9:16 PM
sneeze
sneeze - avatar
+ 1
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"; //startInfo.Arguments = @"-Command echo 'hallo' >> C:\Temp\File1.txt"; startInfo.Arguments = @"-Command echo $ordi = $env:computername >> C:\Temp\File2.txt"; process.StartInfo = startInfo; process.Start(); I liked you idea, so I did give it another try I have tested this code and it works. as in cmd.exe you need /C to execute the command in powershell you need -Command the command you want to execute is echo You need the @-sign to make sure the $ and \ are not control characters Some links that might be interresting for you https://blogs.msdn.microsoft.com/kebab/2014/04/28/executing-powershell-scripts-from-c/ https://www.simple-talk.com/dotnet/net-development/using-c-to-create-powershell-cmdlets-the-basics/ http://codecube.net/2009/11/executing-powershell-scripts-via-c/
8th Jun 2017, 9:34 PM
sneeze
sneeze - avatar
0
Why i would like to write in c# script powershell ? it's because if i create a file, other people will see the script code of the .ps1 file.
7th Jun 2017, 9:53 AM
Attitude
Attitude - avatar
0
Good point. That makes sense.
7th Jun 2017, 8:07 PM
sneeze
sneeze - avatar
0
Thank you sneeze. I will test it again according to your suggestion.
9th Jun 2017, 8:22 PM
Attitude
Attitude - avatar