[英]Calling powershell script with C# - passing in string array as argument in powershell
I am writing C# code to execute a powershell script.我正在编写 C# 代码来执行 powershell 脚本。 The powershell script has two arguments:
powershell 脚本有两个参数:
Problem:问题:
Here is my code: Note that chefRepo is the path of the powershell script.这是我的代码:注意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();
}
For passing an array as powershell argument you need to separate it's values by commas ie for integers you would pass eg 1,2,3
.要将数组作为 powershell 参数传递,您需要用逗号分隔它的值,即对于整数,您将传递例如
1,2,3
。 For string you need additional quotation marks (in case some items contain space) eg 'first string','second string','third'
.对于字符串,您需要额外的引号(以防某些项目包含空格),例如
'first string','second string','third'
。 In C# you would do this by在 C# 中,你可以通过
string.Join(',', resourceGroupNames.Select(x => "'" + x + "'"))
In order to make this approach work when calling by ProcessStartInfo
you need to use powershell option -Command
so that the array would be parsed correctly (see more details in question ).为了在通过
ProcessStartInfo
调用时使这种方法起作用,您需要使用 powershell 选项-Command
以便正确解析数组(请参阅有关问题的更多详细信息)。
Concerning your second problem use powershell commandline option -ExecutionPolicy UnRestricted
关于您的第二个问题,请使用 powershell 命令行选项
-ExecutionPolicy UnRestricted
Finally you just need to change your Arguments
like this:最后你只需要像这样改变你的
Arguments
:
startInfo.Arguments = String.Format("-ExecutionPolicy UnRestricted -Command &\"'{0}\\AzurePowerShellScripts\\azureVMStatusFetch.ps1' - subscriptionId {1} -resourceGroupNames {2}\"", chefRepo, subscriptionId, string.Join(',', resourceGroupNames.Select(x => "'" + x + "'")));
or easier (for C# 7.0 or higher)或更简单(对于 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.