在调用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。 []两个对象的数组:
这就是为什么$ newVM.Name返回$ null但$ V.Name返回VM对象的名称属性(“ testvm1”)的原因
有人可以解释它是如何工作的吗?必须存在一些奇怪的输出绑定。
PS。确实正确创建了一个新的VM!
答案 0 :(得分:0)
我尝试在运行相同版本的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并检查是否有帮助吗?如果没有,您可以增加几秒钟的等待/睡眠时间。