簡體   English   中英

使用 C# 調用 powershell 腳本 - 在 powershell 中將字符串數組作為參數傳遞

[英]Calling powershell script with C# - passing in string array as argument in powershell

我正在編寫 C# 代碼來執行 powershell 腳本。 powershell 腳本有兩個參數:

  1. 字符串類型的訂閱 ID
  2. 類型為 string[] 的資源組名稱

問題:

  1. 運行 C# 程序時,powershell 腳本不會讀取傳遞給 a 的 resourceGroupNames。
  2. 此外,在運行 C# 程序時,powershell 會提示我一條消息“您要運行此腳本嗎?” 無論如何要抑制此警報並讓 powershell 腳本自動運行?

這是我的代碼:注意chefRepo 是powershell 腳本的路徑。

public void DoDeploymentRTM(string chefRepo, string subscriptionId, string[] resourceGroupNames)
        {
            ProcessStartInfo startInfo = new ProcessStartInfo();
            startInfo.FileName = @"powershell.exe";
            startInfo.Arguments = String.Format(@"& '{0}\AzurePowerShellScripts\azureVMStatusFetch.ps1' -subscriptionId {1} -resourceGroupNames {2}", chefRepo, subscriptionId, resourceGroupNames);
            startInfo.Verb = "runas";
            Process process = new Process();
            process.StartInfo = startInfo;
            process.Start();
            process.WaitForExit();
        }

要將數組作為 powershell 參數傳遞,您需要用逗號分隔它的值,即對於整數,您將傳遞例如1,2,3 對於字符串,您需要額外的引號(以防某些項目包含空格),例如'first string','second string','third' 在 C# 中,你可以通過

string.Join(',', resourceGroupNames.Select(x => "'" + x + "'"))

為了在通過ProcessStartInfo調用時使這種方法起作用,您需要使用 powershell 選項-Command以便正確解析數組(請參閱有關問題的更多詳細信息)。

關於您的第二個問題,請使用 powershell 命令行選項-ExecutionPolicy UnRestricted

最后你只需要像這樣改變你的Arguments

startInfo.Arguments = String.Format("-ExecutionPolicy UnRestricted -Command &\"'{0}\\AzurePowerShellScripts\\azureVMStatusFetch.ps1' - subscriptionId {1} -resourceGroupNames {2}\"", chefRepo, subscriptionId, string.Join(',', resourceGroupNames.Select(x => "'" + x + "'")));          

或更簡單(對於 C# 7.0 或更高版本)

startInfo.Arguments = $"-ExecutionPolicy UnRestricted -Command &\"'{chefRepo}\\AzurePowerShellScripts\\azureVMStatusFetch.ps1' - subscriptionId {subscriptionId} -resourceGroupNames {string.Join(',', resourceGroupNames.Select(x => $"'{x}'"))}\"";

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM