欢迎来到我的的博客园,祝大家学有所成,早点实现自己的人生理想。

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();

 

posted @ 2016-12-21 19:46  宋兴柱  阅读(1926)  评论(0编辑  收藏  举报