[英]Calling powershell script with C# - passing in string array as argument in powershell
我正在編寫 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.