C#通过代码调用PowerShell
Posted 宋兴柱-Sindrol
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了C#通过代码调用PowerShell相关的知识,希望对你有一定的参考价值。
var userId = "MyAccount@XXXXX.partner.onmschina.cn"; var tenantId = "XXXXX-ca13-4bcb-840d-d3c1638f63b1"; var tenantDomain = "XXXX.partner.onmschina.cn"; var subscriptionId = "XXXXXX-1fb0-4df7-8737-11b8d6bf88ed"; var subscriptionName = "ZS0_Sub_OTR"; WindowsAzure.Commands.Common.AzureRmProfileProvider.Instance.Profile = new AzureRMProfile("D:\\XXXX.json"); var azureAccount = new AzureAccount() { Id = userId, Type = AzureAccount.AccountType.User }; var env = AzureEnvironment.PublicEnvironments["AzureChinaCloud"]; var subscript = new AzureSubscription() { Id = Guid.Parse(subscriptionId), Name = subscriptionName }; var azureContext = new AzureContext(subscript, azureAccount, env, new AzureTenant { Domain = tenantDomain, Id = Guid.Parse(tenantId) }); WindowsAzure.Commands.Common.AzureRmProfileProvider.Instance.Profile.Context = azureContext; WindowsAzure.Commands.Common.AzureRmProfileProvider.Instance.Profile.Save(); System.Management.Automation.PowerShell ps = System.Management.Automation.PowerShell.Create(System.Management.Automation.RunspaceMode.NewRunspace); ps.Commands.Clear(); ps.AddCommand("Login-AzureRmAccount"); ps.Commands.Commands[ps.Commands.Commands.Count - 1].Parameters.Add("-EnvironmentName", "AzureChinaCloud"); var objs = ps.Invoke(); foreach (var item in objs) { Console.WriteLine(item); } ps.Commands.Clear(); ps.Commands.AddCommand("Set-AzureRmContext"); ps.Commands.Commands[ps.Commands.Commands.Count - 1].Parameters.Add("-SubscriptionName", "ZS0_Sub_OTR"); var sub = ps.Invoke(); //ps.Commands.Clear(); //ps.Commands.AddCommand("Save-AzureRmProfile"); //ps.Commands.Commands[ps.Commands.Commands.Count - 1].Parameters.Add("-Path", "D:\\XXXX.json"); //sub = ps.Invoke(); ps.Commands.Clear(); ps.Commands.AddCommand("Get-AzureRmKeyVault"); ps.Commands.Commands[ps.Commands.Commands.Count - 1].Parameters.Add("-VaultName", "SxzKeyVault"); var result = ps.Invoke(); ps.Commands.Clear(); ps.Commands.AddCommand("New-AzureRmKeyVault"); ps.Commands.Commands[ps.Commands.Commands.Count - 1].Parameters.Add("-VaultName", "SxzKeyVault3"); ps.Commands.Commands[ps.Commands.Commands.Count - 1].Parameters.Add("-ResourceGroupName", "YungoalTest"); ps.Commands.Commands[ps.Commands.Commands.Count - 1].Parameters.Add("-Location", "ChinaNorth"); result = ps.Invoke();
以上是关于C#通过代码调用PowerShell的主要内容,如果未能解决你的问题,请参考以下文章
将c#代码转换为Powershell是不是容易(大约15行代码)