[英]Passing and accessing Powershell parameters from C#
我試圖將參數從C#類傳遞給Powershell腳本。 我正在使用Process.Start
運行腳本。
string powerShellLocation = @"C:\WINDOWS\system32\windowspowershell\v1.0\powershell.exe";
ProcessStartInfo psi = new ProcessStartInfo(powerShellLocation);
psi.Arguments = String.Format("{0} {1}", scriptPath, "some_parameter");
上面的方法不起作用。 有人可以告訴我如何實現嗎?
您需要設置參數名稱。 這樣的事情應該起作用:
string parameters = string.Format("-FILE {0} -parameter1 \"{1}\"", psFilePath, parameter1Value);
Process powershell = new Process()
{
StartInfo = new ProcessStartInfo("powershell.exe", parameters)
{
UseShellExecute = false,
RedirectStandardOutput = true,
RedirectStandardError = true
}
};
您是否將執行策略設置為無限制或是否允許執行腳本。 默認情況下,Powershell將腳本設置為不受限制,以防止運行惡意腳本。
當powershell運行時,以管理員身份運行以下命令:
Get-ExecutionPolicy
你所擁有的會工作。 您沒有提到above does not work
含義above does not work
以及您的腳本是什么。
我用Powershell腳本嘗試了C#代碼:
param([string]$a)
write-host "test"
write-host $a
它給出了輸出:
test
some_parameter
如預期的那樣。 沒有必要指定-File
和-paramter1
像其他的答案中提到,但將取決於你的腳本做什么。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.