gpt4 book ai didi

c# - 对azure vm启动/停止的程序控制

转载 作者:行者123 更新时间:2023-12-03 00:13:28 25 4
gpt4 key购买 nike

我希望我的程序能够启动和停止 azure 虚拟机。我设法编写了一个启动和停止虚拟机的 powershell 脚本,但我想直接从我的 C# 中执行此操作(即,不调用 powershell 脚本)。我没有找到执行此翻译的方法,我将不胜感激帮助。

这是 PowerShell 脚本 函数 stopvm($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# 翻译

提前谢谢

最佳答案

以下是可用于启动虚拟机的代码:

        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

关于c# - 对azure vm启动/停止的程序控制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37359134/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com