首页 > 解决方案 > 如何在 PowerShell 中将 ResourceId 变量转换为字符串?

问题描述

我无法在 PowerShell 中将 ResourceID 转换为字符串。

我有一个列表,其中包含来自 Azure 订阅的每个虚拟接口信息。

$virtualInterfaceArray = @(Get-AzureRmNetworkInterface)

然后我将该列表的索引值放入一个变量中,所以我无法获得我想要的确切信息。例如:

$hostVirtualInterfaceIndex = $virtualInterfaceArray[5]
$hostVirtualInterfaceVM = hostVirtualInterfaceIndex.VirtualMachine

如果我打印 $hostVirtualInterfaceVM 它会返回:

PS C:\Users\marcelo.salvatori> $hostVirtualInterfaceVM
Id                                                                                                                                 
--                                                                                                                                 
/subscriptions/301238dsf0sdfj/resourceGroups/rg-test/providers/Microsoft.Compute/virtualMachines/vmtest

我知道我不能使用 .Split() 方法,因为它不是字符串。所以我尝试使用 .ToString() 方法来解决它:

PS C:\Users\marcelo.salvatori> $hostVirtualInterfaceVMString = hostVirtualInterfaceVM.ToString()

但是,当我打印变量时,它返回:

PS C:\Users\marcelo.salvatori> $hostVirtualInterfaceVMString
Microsoft.Azure.Commands.Network.Models.PSResourceId

我需要这个对话,所以我可以使用 .Split() 方法。

标签: stringpowershellazure

解决方案


如果要获取与该 NIC 关联的虚拟机名称。请尝试使用以下代码。

Get-AzureRmNetworkInterface |  Select-Object -Property Name, @{Name="VMName";Expression = {$_.VirtualMachine.Id.tostring().substring($_.VirtualMachine.Id.tostring().lastindexof('/')+1)}}

推荐阅读