我希望我的程序能够启动和停止azure vm。我设法编写了一个启动和停止VM的powershell脚本,但是我想直接从我的C#中完成它(也就是说,没有调用powershell脚本。我没有设法找到这种翻译的方式,我会很感激帮助。
这是PowerShell脚本 function 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#转换
提前谢谢
答案 0 :(得分:0)
以下是可用于启动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包: