通过Powershell获取与Azure ARM VM的NIC集关联的当前IP地址

时间:2016-06-27 12:55:19

标签: powershell azure azure-resource-manager

我正在尝试编写一些Powershell来获取Azure ARM vms(非经典)列表以及其NIC的当前关联IP地址。

在经典中,这是VM对象的一部分,但在ARM中它是一个单独的对象,我正在努力让Powershell以我想要的方式工作。

我有以下代码段:

setFocusedCell(rowIndex, colKey, floating)

哪个有效,但仅适用于指定资源组'RGTEST'中的VM。

似乎Get-AzureRmNetworkInterface只能在NIC Name和ResourceGroupName中传递时工作,但我似乎无法从VM传入RGname。

可能真的很容易,但我正在苦苦挣扎!

6 个答案:

答案 0 :(得分:8)

我使用此代码获取所有ARM虚拟机,其私有IP地址和分配方法,它适用于资源组。

$vms = get-azurermvm
$nics = get-azurermnetworkinterface | where VirtualMachine -NE $null #skip Nics with no VM

foreach($nic in $nics)
{
    $vm = $vms | where-object -Property Id -EQ $nic.VirtualMachine.id
    $prv =  $nic.IpConfigurations | select-object -ExpandProperty PrivateIpAddress
    $alloc =  $nic.IpConfigurations | select-object -ExpandProperty PrivateIpAllocationMethod
    Write-Output "$($vm.Name) : $prv , $alloc"
}

样品输出:
proddc:10.0.0.4,静态
stagedc:10.1.0.4,静态

答案 1 :(得分:1)

以下是我用于获取Azure ARM VM的专用IP和公用IP的脚本。如果VM有多个NIC或IpConfig,则可能需要使用循环。

$rg = Get-AzureRmResourceGroup -Name "MyResourceGroup01"
$vm = Get-AzureRmVM -ResourceGroupName $rg.ResourceGroupName -Name "MyVM01"
$nic = Get-AzureRmNetworkInterface -ResourceGroupName $rg.ResourceGroupName -Name $(Split-Path -Leaf $VM.NetworkProfile.NetworkInterfaces[0].Id)
$nic | Get-AzureRmNetworkInterfaceIpConfig | Select-Object Name,PrivateIpAddress,@{'label'='PublicIpAddress';Expression={Set-Variable -name pip -scope Global -value $(Split-Path -leaf $_.PublicIpAddress.Id);$pip}}
(Get-AzureRmPublicIpAddress -ResourceGroupName $rg.ResourceGroupName -Name $pip).IpAddress

#Output:    
Name      PrivateIpAddress PublicIpAddress
----      ---------------- ---------------
ipconfig1 10.0.0.10        MyVM01-pip

40.80.217.1

答案 2 :(得分:0)

这是我用来获取用于各种任务的相关VM专用/公共IP地址信息的脚本。它会从MAC OS或Windows OS运行,因为我有一个运行Widows 10 Parallels VM的MAC以实现兼容性。根据需要使用它。

它将导出为CSV并尝试在Excel中打开或尝试在CSV扩展名中注册任何内容。在下面的示例中,将其另存为PS_AzureRM_Get_VMs.ps1或仅将其作为原始代码在PowerShell中运行。

#Login to AZURE from PowerShell
#Below works in MAC/Linux PowerShell 6.0.1+ and Windows WMF 4.0+
#pwsh on MAC OS or powershell_ise.exe on Windows
#Connect-AzureRmAccount (Login-AzureRMAcount and Add-AzureRMAccount are the older Azure cmdlets)
# Goto URL https://microsoft.com/devicelogin and the password it provides example Q9KZ3HGN2
#  You may need to select-azurermsubscription -subscriptionid $SubscriptionID #Define $SubscriptionID = 'replace everything with your actual subscription  xxx-xxxx-xxx'

#Example location using the . way of running a script or just cut and paste to PowerShell
#Example location using the . way of running a script
#MAC PWSH syntax
#. ~/Documents/Scripts/AzureRM/PS_AzureRM_Get_VMs.ps1
#Windows PowerShell.exe/PowerShell_ISE.exe syntax
#. $env:userprofile\Scripts\AzureRM\PS_AzureRM_Get_VMs.ps1

$Project="DevOps"
$clientFilePrefix="AzureRM"
$clientFileCampaign="VMs"

#Get Date Time
$Date = ([DateTime]::Now).ToString("yyyyMMdd")
$Time = ([DateTime]::Now).ToString("HHmmss")
$DateStart=get-date

#Change to Windows Path if running in Windows $env:USERPROFILE
If ($($env:USERPROFILE)) {
  $fldrRoot="$($env:USERPROFILE)\"
  $fldrPathseparator='\'
} Else {
  $fldrRoot="~/"
  $fldrPathseparator='/'
}

# Make Directory if not exist
$fldrPath=$fldrRoot+"Documents"+$fldrPathseparator+$Project+$fldrPathseparator+$clientFilePrefix+$fldrPathseparator+$clientFileCampaign
New-Item -ErrorAction Ignore -ItemType directory -Path $fldrPath

#Make Imports Folder
$fldrPathimports=$fldrPath+$fldrPathseparator+"Imports"
New-Item -ErrorAction Ignore -ItemType directory -Path $fldrPathimports

#Make Exports Folder Directory
$fldrPathexports=$fldrPath+$fldrPathseparator+"Exports"
New-Item -ErrorAction Ignore -ItemType directory -Path $fldrPathexports

#Assign the variable to the export file Prefix
$VMInfo_Export=$fldrPathexports+$fldrPathseparator+$clientFilePrefix+"_"+$Project+"_"+$clientFileCampaign+"_"+$Date+"_"+$Time+".csv"

#Create a Table to use for filtering the results
$VMInfo = New-Object System.Data.DataTable
#Now Add some columns for use later
$VMInfo.Columns.Add((New-Object System.Data.DataColumn 'ResourceGroup',([String])))
$VMInfo.Columns.Add((New-Object System.Data.DataColumn 'VM',([String])))
$VMInfo.Columns.Add((New-Object System.Data.DataColumn 'Location',([String])))
$VMInfo.Columns.Add((New-Object System.Data.DataColumn 'VM_ID',([String])))
$VMInfo.Columns.Add((New-Object System.Data.DataColumn 'VM_NIC',([String])))
$VMInfo.Columns.Add((New-Object System.Data.DataColumn 'IP',([String])))
$VMInfo.Columns.Add((New-Object System.Data.DataColumn 'Public_IP_Name',([String])))
$VMInfo.Columns.Add((New-Object System.Data.DataColumn 'Public_IP',([String])))
$VMInfo.Columns.Add((New-Object System.Data.DataColumn 'IP_MAC',([String])))
$VMInfo.Columns.Add((New-Object System.Data.DataColumn 'Priv_Dyn',([String])))
$VMInfo.Columns.Add((New-Object System.Data.DataColumn 'Status',([String])))
$VMInfo.Columns.Add((New-Object System.Data.DataColumn 'Date_Time',([String])))
$VMInfo_Array_Count=($VMInfo | Measure-Object | Select Count).Count

#List the Array to show it='s empty
Write-Host "Created Array VMInfo with $VMInfo_Array_Count objects"

$Date_Time=([DateTime]::Now).ToString("yyyy/MM/dd")+" "+([DateTime]::Now).ToString("HH:mm:ss")
#Check the OS type
If ($($ENV:OS)) {$OSTYPE="WINDOWS";Write-Host "The OS is"$OSTYPE" Based"} Else {$OSTYPE="LINUX";Write-Host "The OS is"$OSTYPE" Based"}
#Get the VM's
$VMs = Get-AzureRmVM
$VMstatus = Get-AzureRmVM -Status
#Get the NIC and their properties for matching against the VMs
$NICs = get-azurermnetworkinterface | where VirtualMachine -NE $null #skip NICs with no VM
#Get the Public IPs for matching against the VMs
#Public IPs work only if the naming convention starts with the VM Name used in Azure
$PublicIPs=Get-AzureRmPublicIpAddress | Select-Object Name,ResourceGroupName,IpAddress

#Now Loop through the NICs in Azure and match against the VMs and the Public IPs
ForEach ($nic in $NICs)
{
    #Get the VM Info
    $VM = $VMs | where-object -Property Id -EQ $nic.VirtualMachine.id
    $VM_Name = $($VM.name)
    $VM_Location = $($VM.Location)
    $VM_Resourcegroup = $($VM.ResourceGroupName)
    $VM_ID = $($VM.VMid)
    $VM_NIC = $nic.Name -Join ';'
    $VM_Status = (($VMstatus | Where {$_.ResourceGroupName -eq $VM_Resourcegroup -and $_.Name -eq $VM_Name}).PowerState).Replace('VM ', '')
    $VM_IP =  ($nic.IpConfigurations | select-object -ExpandProperty PrivateIpAddress) -Join ';'
    $VMPIPName = ($nic.IpConfigurations.PublicIpAddress.Id -Split '/')[-1]
    $VM_PublicIP =  ($PublicIPs | Where-Object {$_.ResourcegroupName -eq $VM_Resourcegroup -and $_.Name -like "$VMPIPName"} | Select IpAddress).IpAddress
    $VM_IP_MAC =  (($nic | Select MacAddress).MacAddress) -Join ';'
    $VM_Alloc =  $nic.IpConfigurations | select-object -ExpandProperty PrivateIpAllocationMethod

    #Uncomment this to check the values before going into the Array $VMINFO
    #Write-Output "$($VM.ResourceGroupName), $($VM.Name), $($VM.VMid), $($VM.Location), $VM_IP, $VM_PublicIP, $VM_IP_MAC, $VM_Alloc"

    #Now populate the $VMInfo array
    $row = $VMInfo.NewRow()
    $row.'ResourceGroup'=$VM_Resourcegroup
    $row.'VM'=$VM_Name
    $row.'VM_ID'=$VM_ID
    $row.'VM_NIC'=$VM_NIC
    $row.'Location'=$VM_Location
    $row.'IP'=$VM_IP
    $row.'Public_IP_Name'=$VMPIPName
    $row.'Public_IP'=$VM_PublicIP
    $row.'IP_MAC'=$VM_IP_MAC
    $row.'Priv_Dyn'=$VM_Alloc
    $row.'Status'=$VM_Status
    $row.'Date_Time'=$Date_Time
    $VMInfo.Rows.Add($row)
}
cls
$TotalTime=(NEW-TIMESPAN –Start $DateStart –End $(GET-DATE))
Write-Host "Script Ran in $($TotalTime.Hours) hours and $($TotalTime.Minutes) minutes and $($TotalTime.Seconds) seconds"

#Export the Info
Write-Host "Exporting VMINFO Report to `n`t$($VMInfo_Export)"
$VMInfo | Export-CSV -NoTypeInformation -Path $VMInfo_Export

#Depending on OS run the Open/Start command for the CSV Export
If ($OSTYPE -eq "LINUX") {open $VMInfo_Export} `
ElseIf ($OSTYPE -eq "WINDOWS") {start $VMInfo_Export} `
Else {Write-Host "Unknown OS"}

break

#####     ######     #####
#######     ######     #####
##     Extra Tasks to Filter the Exports
#####     ######     #####
#######     ######     #####

#Get the Array Size
$VMInfo_Array_Count=($VMInfo | Measure-Object | Select Count).Count

#ECHO the Array size
Write-Host "`n`n*****     *****"
Write-Host "Array VMInfo has $VMInfo_Array_Count objects"
Write-Host "*****     *****"

break
#Shows Configured Resource Group Names
$VMInfo_ResourceGroupNames=($vminfo | Select ResourceGroup -Unique).ResourceGroup

#ECHO Configured Resource Group Names
Write-Host "`n`n*****     *****"
Write-Host "*****     List of Groups*****"
Write-Host "*****     *****"
$($VMInfo_ResourceGroupNames)

break
#Get DC's from resource Group Name
$VM_Environment="dtdaily"
$VMInfo_GetDCs=$vminfo | where {$_.ResourceGroup -eq $VM_Environment -and $_.VM -like "*dc*"}

#ECHO DC's from resource Group Name
Write-Host "`n`n*****     *****"
Write-Host "*****     List of DC's"
Write-Host "*****     *****"
$($VMInfo_GetDCs)

break
#Get Public IP VMs
$VMInfo_PublicIPs=$vminfo | Where {$_.Public_IP -like "*.*"}

#ECHO Public IP VMs
Write-Host "`n`n*****     *****"
Write-Host "*****     *****"
Write-Host "*****     List of Public IP VMs"
Write-Host "*****     *****"
$($VMInfo_PublicIPs)

break
#ECHO All VMs
$VMInfo

Break

答案 3 :(得分:0)

自2016年提出此问题以来,Microsoft决定不再维护Dec 2020之后的AzureRM模块,并不再维护*-AzureRM* cmdlet。 Az模块取代了它。

但是,有一种快速替代方法,可以使用Azure资源图(ARG)检索具有关联IP(私有和公用IP)的Azure VM列表。

对于数以千计的VM,分布在数百个Azure订阅中,使用ARG只需几秒钟,而使用Az的{​​{1}} cmdlet则需要20分钟以上

即使在多个vmNics和每个vmNic的多个IP配置上,脚本也会向下正确报告。它将在租户中跨Azure订阅检索所有ARM VM数据。如果从本地Powershell会话或Cloud Shell运行,请确保首先安装了Get-AzVM模块。

在一个小型测试Azure租户上的输出示例:

enter image description here

脚本如下:

Az.ResourceGraph

如果还要使用ARG检索经典的Azure VM(ASM模型),则可以使用脚本here。可以在this post中找到有关用于检索VM数据,限制,权限等的Azure资源图查询的详细讨论。

答案 4 :(得分:-1)

我搜索了很多,终于成功了。使用资源组名称和azure vm名称,您可以检索私有或公共IP地址:

$Resourcegroup=""

$VmName=""

$VmNetworkdetails= (((Get-AzureRmVM -ResourceGroupName $Resourcegroup -Name $VmName).NetworkProfile).NetworkInterfaces).Id

$nicname = $VmNetworkdetails.substring($VmNetworkdetails.LastIndexOf("/")+1)

$privateIp =(Get-AzureRmNetworkInterface -Name $nicname -ResourceGroupName $Resourcegroup)|Select-Object -ExpandProperty IPConfigurations 

write-host $privateIp.PrivateIpAddress

答案 5 :(得分:-1)

对于那些正在寻找可在租户中跨多个订阅使用的解决方案的人来说,以下是一个脚本,该脚本循环遍历每个订阅并报告每个私有IP,NIC,VM,资源组和关联的订阅。输出为对象格式,并导出到CSV文件。

<#
    .SYNOPSIS
        Returns IP addresses and associated network interfaces and virtual machines across all Azure subscriptions the
        user has access to.

    .DESCRIPTION
        This script returns all private IP addresses, the IP configuration resources they are associated with, the network interfaces and virtual
        machines across all subscriptions. This script requires:

        1. The Azure module to be installed (https://docs.microsoft.com/en-us/powershell/azure/install-az-ps?view=azps-2.8.0)
        2. The user to be logged in to an Azure account using Connect-AzAccount / Connect-AzureRmAccount
        3. The user must have subscription wide read permissions assigned for each subscription being queried

    .PARAMETER FileName
        Optional. Specify the file name and path for a CSV export.

    .EXAMPLE
        Get-IpAddressAllocation.ps1 -FileName .\AzureIpAddressReport.csv
#>

<#
    .AUTHOR
        Michael Wheatfill

    .LICENSEURI
        https://github.com/mwheatfill/mwheatfill.github.io/blob/master/LICENSE.txt
#>

#region Parameters
[CmdletBinding()]
param (
    [Parameter(Mandatory=$true)]
    [ValidateNotNullOrEmpty()]
    [String]
    $FileName
)
#endregion Parameters

#region Initializations
Set-StrictMode -Version Latest
$ErrorActionPreference = "Stop"
#endregion Initializations

#region Functions
function Get-IpAddresses {
    param ()

    $networkInterfaces = Get-AzNetworkInterface | Where-Object {$_.VirtualMachine -ne $null}
    $virtualMachines = Get-AzVM
    $results = @()

    foreach($interface in $networkInterfaces) {
        $ipConfigurations = $interface.IpConfigurations

        foreach($ipConfig in $ipConfigurations) {
            $vm = $virtualMachines | Where-Object {$_.Id -eq $interface.VirtualMachine.Id}

            $ipDetails = [pscustomobject]@{
                PrivateIpAddress = $ipConfig.PrivateIpAddress
                VMName = $vm.Name
                NetworkInterface = $interface.Name
                IpConfigName = $ipConfig.Name
                Primary = $ipConfig.Primary
                ResourceGroup = $vm.ResourceGroupName
                Subscription = $subscription.Name
            }
            $results += $ipDetails
        }
    }
    return $results
}
#endregion Functions

#region Main
$subscriptions = Get-AzSubscription | Select-Object
$ipAddressesInAllSubscriptions = @()
$progressCount = 0

foreach ($subscription in $subscriptions) {
    $progressCount++
    $progressComplete = ($progressCount / $subscriptions.count * 100)
    $progressMessage = "Gathering IP address informtion for subscription $progressCount of $($subscriptions.Count)"
    Write-Progress -Activity $progressMessage -Status ($subscription.Name) -PercentComplete $progressComplete

    $subscription | Select-AzSubscription > $null
    $ipAddressesInSubscription = Get-IpAddresses -SubscriptionObject $subscription
    $ipAddressesInAllSubscriptions += $ipAddressesInSubscription
}

$ipAddressesInAllSubscriptions | Sort-Object -Property Subscription, VMName, NetworkInterface, IpConfigName, Primary | Format-Table
$ipAddressesInAllSubscriptions | Export-Csv -Path $FileName -NoTypeInformation
#endregion Main
相关问题