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);
CodePudding user response:
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:
movefile.Arguments =
$@"-NoProfile -Command "" Copy-Item -Path \""{flocation}\W11F-assets\"" -Destination \""C:\Windows\W11F-assets\"" -Recurse "" ";
CodePudding user response:
Was able to solve issue by replacing \"
with '
.