2

I'm unable to pass through an argument to powershell which contains "". When I use the equivalent code but change the application to cmd the "" are able to pass through.

The argument I'd like powershell to execute is:

Copy-Item -Path "{Working Directory}\W11F-assets\" -Destination "C:\\Windows\W11F-assets" -Recurse

This is the code that's calling that function:

    ProcessStartInfo movefile = new ProcessStartInfo("powershell.exe");
    string flocation = Directory.GetCurrentDirectory();
    movefile.UseShellExecute = true;
    movefile.Arguments = "Copy-Item -Path \"" + flocation + "\\W11F-assets\" -Destination \"C:\\Windows\\W11F-assets\" -Recurse";
    Process.Start(movefile);
jessehouwing
  • 106,458
  • 22
  • 256
  • 341
99natmar99
  • 33
  • 6
  • You have a lot of escaping issues. You can tell this by looking at the syntax highlighting. If this is literally part of the command: `"C:\\Windows\W11F-assets"` then I am guessing you meant to escape both slashes, not just the first one. And in your actual C# code, you need to escape every single slash, so those \\ are going to look like \\\\ in the C# source. Also note the first \" in the command, did you mean to escape that? – AndrewF Feb 18 '22 at 01:15

2 Answers2

1

When commands are passed to the PowerShell CLI's (positionally implied) -Command (-c) parameter, any unescaped " chars. are stripped during command-line processing, and only then are the arguments (space-joined to form a single string, if there are multiple ones) interpreted as PowerShell code.

Therefore:

  • " characters that are to be retained as part of the command(s) must be \"-escaped.

  • Additionally, to prevent potentially unwanted whitespace normalization (folding multiple adjacent spaces into one), it is best to enclose the command(s) in unescaped embedded "..." overall.

To fully spell out a solution that should work, with explicit use of -Command and also -NoProfile to avoid usually unnecessary loading of the profile files, and with extra spaces for conceptual clarity, taking advantage of interpolated ($) verbatim (@) strings (inside of which \ can be used as-is and " must be escaped as ""):

movefile.Arguments = 
  $@"-NoProfile -Command "" Copy-Item -Path \""{flocation}\W11F-assets\"" -Destination \""C:\Windows\W11F-assets\"" -Recurse "" "; 
mklement0
  • 382,024
  • 64
  • 607
  • 775
0

Was able to solve issue by replacing \" with '.

mklement0
  • 382,024
  • 64
  • 607
  • 775
99natmar99
  • 33
  • 6
  • 1
    That's a viable workaround, but it's important to note that it would require extra work for paths that themselves happen to contain `'` characters. A proper solution with `"` quoting is possible, which works will all paths as-is, given that paths cannot contain `"` characters (on Windows). – mklement0 Feb 17 '22 at 22:33