azure - Azure Powershell 脚本
问题描述
我编写了一个 PowerShell 脚本来打印带有非托管磁盘的 VM 名称,但是它给了我一个错误。感谢对此的任何帮助-
$location=Read-Host -Prompt 'Input location for VMs'
$azuresubscription=Read-Host -Prompt 'Input Subscription Id'
$rmvms=Get-AzurermVM
# Add info about VM's from the Resource Manager to the array
foreach ($vm in $rmvms)
{
# Get status (does not seem to be a property of $vm, so need to call Get-AzurevmVM for each rmVM)
$vmstatus = Get-AzurermVM -Name $vm.Name -ResourceGroupName $vm.ResourceGroupName -Status | where Location -like $location
# Add values to the array:
$vmarray += New-Object PSObject -Property @{`
# Subscription=$Subscription.SubscriptionName; `
Subscription=$azuresubscription.SubscriptionName; `
AzureMode="Resource_Manager"; `
Name=$vm.Name; PowerState=(get-culture).TextInfo.ToTitleCase(($vmstatus.statuses)[1].code.split("/")[1]); `
Size=$vm.HardwareProfile.VirtualMachineSize}
}
foreach ($vm in $vmarray)
{
$vmdiskstatus = (Get-AzurermVM -Name $vm.Name -ResourceGroupName $vm.ResourceGroupName).StorageProfile.OsDisk.ManagedDisk
if (!$vmdiskstatus) {Write-Host $vm.Name}
}
错误信息:
($vmarray 导致空数组) -
无法索引到空数组。
预期输出 - $vmarray 应该有一个虚拟机,因为eastus 中有一个正在运行的实例(这就是我用作 $location 的值)
解决方案
根据维克多席尔瓦的要求,将我的评论添加为答案,这里是:
您需要$vmarray
在进入循环之前定义 as 数组以向其中添加对象。然后,在那个循环之后,即使是空的,也foreach ($vm in $vmarray)
确实有一个要索引的数组:
$location=Read-Host -Prompt 'Input location for VMs'
$azuresubscription=Read-Host -Prompt 'Input Subscription Id'
$rmvms=Get-AzurermVM
###################################################
# create an array variable to collect the result(s)
###################################################
$vmarray = @()
# Add info about VM's from the Resource Manager to the array
foreach ($vm in $rmvms)
{
# rest of your code
}
推荐阅读
- laravel - Laravel - 试图获取非对象的属性'employee_code'
- jwt - 在 SignalR 与 Blazor-WASM 连接期间使用 JWT
- python - 挑战:使用 python 提取曲线文本
- javascript - 我需要在具有特定条件的数组中找到重复的行
- python - 在让用户使用命令之前,我需要我的电报机器人询问密码
- github - 我在克隆文件时遇到错误。这是说我没有访问权限,而我的同事可以从该存储库中克隆它
- node.js - Azure Kubernetes 服务 - 为非管理员 AD 应用程序身份获取 kubeconfig
- java - 将对象写入通量
- vba - Selenium Chromedriver 无法正确填写密码
- c# - 将 linq 查询包装到 if 语句中(不同的查询选项取决于 if 语句)