对 Azure VM 启动/停止的程序控制



我希望我的程序能够启动和停止 Azure VM。我设法编写了一个启动和停止 VM 的 powershell 脚本,但我想直接从我的 C# 执行此操作(也就是说,无需调用 powershell 脚本。我没有设法找到进行此翻译的方法,我将不胜感激。

下面是 PowerShell 脚本 函数停止VM($resourcegroup,$vmname) { Stop-AzureRmVM -ResourceGroup $resourcegroup -Name $vmname }

function startvm($resourcegroup,$vmname) 
{ 
    Start-AzureRmVM -ResourceGroup $resourcegroup -Name $vmname 
} 
################################################################ 
# Please Change These Variables to Suit Your Environment 
# 

 $subscriptionname = "Subscription Name"
 $resourcegroup = "Resource Group Name" 
 $vmname = "VM name"
 ################################################################ 
 Login-AzureRmAccount -SubscriptionName $subscriptionname
 write-host "Choose the options to Start and Stop your Azure VMS" 
    write-host "1. Start VM" 
    write-host "2. Stop VM" 
 $answer = read-host "Please Select Your Choice" 
 Switch($answer) 
 { 
    1{ StartVM $resourcegroup $vmname} 
    2{ StopVM $resourcegroup $vmname} 
 }

主要障碍是找到 Login-AzureRm 的 C# 翻译

提前谢谢你

下面是可用于启动 VM 的代码:

        AuthenticationContext context = new AuthenticationContext("[OAUTH2 AUTHORIZATION ENDPOINT]");
        UserCredential userCred = new UserCredential("[CO-ADMINISTRATOR E-MAIL]", "[CO-ADMINISTRATOR PASSWORD]");
        AuthenticationResult result = context.AcquireTokenAsync("https://management.core.windows.net/", "[APPLICATION CLIENT ID]", userCred).Result;
        TokenCloudCredentials credentials = new TokenCloudCredentials("[SUBSCRIPTION ID]", result.AccessToken);
        using (ComputeManagementClient computeClient = new ComputeManagementClient(credentials))
        {
            computeClient.VirtualMachines.Start("[CLOUD SERVICE NAME]", "[DEPLOYMENT NAME]", "[VM NAME]");
        }

编辑:

这需要安装以下 NuGet 包:

Microsoft.WindowsAzure.Management.Compute

Microsoft.IdentityModel.Clients.ActiveDirectory

相关内容

最新更新