[英]Powershell invoke-restmethod variable in url
I am new to powershell, and I am trying to create a simple script that will allow me to turn on several Azure VMs using the invoke-restmethod.我是 powershell 的新手,我正在尝试创建一个简单的脚本,允许我使用 invoke-rest 方法打开多个 Azure VM。
My code works when instead of using a variable I directly write the VM name into the url, but I want to use a variable, since eventually this must work for more than one VM.当我没有使用变量而是直接将 VM 名称写入 url 时,我的代码可以工作,但我想使用变量,因为最终这必须适用于多个 VM。
Relevant part of code:代码的相关部分:
$body = @{
"$virtualMachines" = "VM1"
} | ConvertTo=Json
$url= "https://management.azure.com/subscriptions/mySubscriptionId/resourceGroups/myResourceGroupName/providers/Microsoft.DevTestLab/labs/myLabName/virtualmachines/" + $virtualMachines + "/start?api-version=2018-09-15"
$response = Invoke-RestMethod -uri $url -Method 'POST' -Headers $headers -Body $body
$response | ConvertTo-Json
If you had a number of VMs, you could put them all into a PowerShell variable like this, an array of strings.如果您有多个 VM,则可以将它们全部放入 PowerShell 变量中,就像这样,一个字符串数组。
$VMs = "myVm1", "myVm2", "myVm3"
PowerShell has a number of flow control statements, the one you want to use is ForEach
, which will step through an array one at a time. PowerShell 有许多流控制语句,您要使用的一个是
ForEach
,它将一次遍历一个数组。 We just modify the way you're setting up the URL to be friendlier and easier to read and this should work just fine.我们只是修改了您设置 URL 的方式,使其更友好且更易于阅读,这应该可以正常工作。
$baseUrl = "https://management.azure.com/subscriptions/mySubscriptionId/resourceGroups/myResourceGroupName/providers/Microsoft.DevTestLab/labs/myLabName/virtualmachines/"
ForEach ($vm in $VMs){
$url = $baseurl + $vm + "/start?api-version=2018-09-15"
Write-host "About to start [$Vm]"
$response = Invoke-RestMethod -uri $url -Method 'POST' -Headers $headers
$response | ConvertTo-Json
}
I checked the API documentation for the start?
我检查了 API 文档
start?
REST API endpoint, and it doesn't look like you need the -Body
parameter for this endpoint. REST API 端点,看起来您不需要此端点的
-Body
参数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.