Home > OS >  having trouble with Double Quotes between C# and PowerShell
having trouble with Double Quotes between C# and PowerShell

Time:02-26

This is my code working in powershell, but to put it in C# I must replace "$string" to "$string2"; but it's not working (: it must be "$string" to work... I tried '$string' and ($string) and a lot but just this "$string" working. Help ?

Powershell Code Working 100% :
$string2 = C:/Users/Sycho/Desktop/youtube-dl.exe -F https://youtu.be/f1A7SdVTlok | Out-String -stream | Select-String 133 ; "$string2".SubString(105)
     var mainForm = Application.OpenForms.OfType<Form1>().Single();
     string urlBoxText3 = mainForm.Controls["URL_BOX"].Text;
     ProcessStartInfo startInfo6 = new ProcessStartInfo();
     startInfo6.FileName = @"powershell.exe";
     startInfo6.Arguments = "$string2 = C:/Users/Sycho/Desktop/youtube-dl.exe -F "   urlBoxText3   "| Out-String -stream | Select-String 133 ; \"$string2\".SubString(105)";
     startInfo6.RedirectStandardOutput = true;
     startInfo6.RedirectStandardError = true;
     startInfo6.UseShellExecute = false;
     startInfo6.CreateNoWindow = true;
     startInfo6.Verb = "runas";
     Process process6 = new Process();
     process6.StartInfo = startInfo6;
     process6.Start();
     string output = process6.StandardOutput.ReadToEnd();
     label4.Text = output;

CodePudding user response:

  • You say that PowerShell must ultimately see "$string2".SubString(105) for your command to work.

  • When you call PowerShell via its CLI, powershell.exe, and pass commands to it via the (positionally implied) -Command / -c parameter, you must escape " characters as \" in order for PowerShell to retain them as part of the command(s) to execute after command-line parsing.

Therefore, replace \"$string2\" with \\\"$string2\\\" (sic).


Taking a step back: You could streamline your code as follows, which obviates the need for enclosing $string2 in "..."

startInfo6.Arguments = "$string2 = (C:/Users/Sycho/Desktop/youtube-dl.exe -F "   urlBoxText3   " | Select-String 133).Line; $string2.SubString(105)";
  • By accessing the .Line property on the output object emitted by the Select-String call, a string - the matching line - is directly returned (rather than the match-info object that is emitted by default).

  • Out-String -Stream was removed, because it is unnecessary: PowerShell exhibits this behavior by default when calling external programs such as youtube-dl.exe.

  • Related