[英]Can't pass through "" to powershell using ProcessStartInfo arguments, C#
我無法將參數傳遞給包含""
的 powershell。 當我使用等效代碼但將應用程序更改為 cmd 時, ""
能夠通過。
我希望 powershell 執行的參數是:
Copy-Item -Path "{Working Directory}\W11F-assets\" -Destination "C:\\Windows\W11F-assets" -Recurse
這是調用 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);
當命令被傳遞到 PowerShell CLI 的(位置隱含的) -Command
( -c
) 參數時,任何未轉義的"
字符。在命令行處理期間被剝離,只有這樣arguments(空格連接形成單個字符串,如果有多個)解釋為 PowerShell 代碼。
所以:
"
作為命令的一部分保留的字符必須進行\"
-轉義。
此外,為了防止可能不需要的空白規范化(將多個相鄰空格折疊成一個),最好將命令包含在未轉義的嵌入式"..."
中。
為了充分說明應該有效的解決方案,明確使用-Command
和-NoProfile
以避免通常不必要地加載配置文件,並使用額外的空間來使概念清晰,利用內插 ( $
) 逐字 ( @
) 字符串(其中\
可以按原樣使用, "
必須轉義為""
):
movefile.Arguments =
$@"-NoProfile -Command "" Copy-Item -Path \""{flocation}\W11F-assets\"" -Destination \""C:\Windows\W11F-assets\"" -Recurse "" ";
能夠通過將\"
替換為'
來解決問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.