azure - 调用 New-AzureRmVm 的输出在返回给调用者之前是不可访问的
问题描述
调用 New-AzureRMVM 时,输出包含一个表示创建的 VM 的对象,但在我离开函数之前,该对象是不可访问的。
在下面的代码片段中,在函数 Create-VM 中,输出 ($newVM.Name) 为 $null。但是,如果我将 $newVM 返回给调用者,则 $V.Name 包含一个值。
# PSVersion 5.1.17763.503
Function Create-VM
{
param
(
[Parameter(Mandatory=$true)]
[string]$vmName
# and some others ...
)
# Snipped
try
{
$newVM = New-AzureRMVM -ResourceGroupName $vmResourceGroup # ...
Write-Host "newVM.IsSuccessStatusCode = $($newVM.IsSuccessStatusCode)"
Write-Host "newVM.Name = $($newVM.Name)"
return $newVM
}
catch
{
# Snipped
}
}
$vmName ="testvm1"
$V = Create-VM -vmName $vmName # ....
if ($V)
{
Write-Host $V.GetType() # why does this return System.Object[]?
Write-Host "V.IsSuccessStatusCode = $($V.IsSuccessStatusCode)"
Write-Host "V.Name = $($V.Name)" # why does this return a value???
}
输出如下所示:
WARNING: New-AzureRmVM: A property of the output of this cmdlet will change in an upcoming breaking change release. The StorageAccountType property
for a DataDisk will return Standard_LRS and Premium_LRS
newVM.IsSuccessStatusCode = True
newVM.Name =
System.Object[]
V.IsSuccessStatusCode = True
V.Name = testvm1
在调试器中单步执行此代码,我们可以看到 $newVM 在 Create-VM 函数中是“PSAzureOperationResponse”类型的单个对象,但是当它返回给调用者时,它变成了一个 System.Object[] 数组两个对象:
- $V[0] 是“PSAzureOperationResponse”类型
- $V[1] 是“PSVirtualMachine”类型
这就是为什么 $newVM.Name 返回 $null 但 $V.Name 返回 VM 对象的 name 属性(“testvm1”)
有人可以解释这是如何工作的吗?一定有一些奇怪的输出绑定正在进行。
PS。确实正确创建了一个新虚拟机!
解决方案
我尝试在运行相同版本的 Powershell 5.1.17763.503 和 AzureRM 版本 6.13.1 的机器上执行上面提供的脚本(稍作更改),并且能够在 Create-VM 函数中正常访问 newVM 对象并返回也是。这是脚本和输出:
# PSVersion 5.1.17763.503
# AzureRM 6.13.1
Function Create-VM
{
param
(
[Parameter(Mandatory=$true)]
[string]$vmName
# and some others ...
)
# Snipped
try
{
$newVM = New-AzureRMVM -ResourceGroupName $ResourceGroupName # ...
Write-Host "`nnewVM.StatusCode = $($newVM.StatusCode)" # StatusCode is the property
Write-Host "newVM.Name = $($newVM.Name)"
Write-Host $newVM.GetType()
return $newVM
}
catch
{
Write-Host "in the catch block"
}
}
$vmName ="testvm1"
$V = Create-VM -vmName $vmName # ....
if ($V)
{
Write-Host "`nOut of Create-VM"
Write-Host $V.GetType()
Write-Host "V.StatusCode = $($V.StatusCode)"
Write-Host "V.Name = $($V.Name)"
}
输出:
Supply values for the following parameters:
Name: testvm0
newVM.StatusCode = 0
newVM.Name = testvm0
Microsoft.Azure.Commands.Compute.Models.PSVirtualMachine
Out of Create-VM
Microsoft.Azure.Commands.Compute.Models.PSVirtualMachine
V.StatusCode = 0
V.Name = testvm0
您可以尝试升级到最新版本的AzureRM并检查它是否有帮助?如果没有,您可以添加几秒钟的等待/睡眠时间。
推荐阅读
- javascript - 连接 NextJS、next-i18next、with-redux、with-redux-saga:“错误:如果您的自定义 _app.js 文件中有 getInitialProps 方法...”
- unity3d - 统一 if 语句即使是真的也不会起作用
- python - 列包含列
- c# - 当我尝试将文件复制到“//192.168.0.22”之类的共享路径时,访问被拒绝错误
- android - 如何获取回收站当前可见项目位置
- jquery - 如何格式化通过 AJAX 从 ASPX JSON 解析的日期?
- css - 有没有办法在反应中使用我的样式作为外部 css 文件?
- c - C中寄存器存储类的存储分配?
- cypress - 如何让赛普拉斯只处理可见元素?
- python - 如何解释 scipy.interpolate.splrep 的结果?