簡體   English   中英

是否有任何 Powershell 腳本,或者如果虛擬機有多個 ip 地址,我如何修改此腳本以將多個 ip 作為 csv 文件導入?

[英]Is there any Powershell script or how can i modify this script to import multiple ips as a csv file if a vm has multiple ip addresses?

是否有任何 Powershell 腳本,或者如果虛擬機有多個 ip 地址,我如何修改此腳本以將多個 ip 作為 csv 文件導入? 這是我現有的腳本

# Create Report Array
$report = @()

# Get all the VMs from the selected subscription
$vms = Get-AzVM

# Get all the Network Interfaces
$nics = Get-AzNetworkInterface | Where-Object { $_.VirtualMachine -NE $null } 

foreach ($nic in $nics) {

$ReportDetails = "" | Select-Object  ip-address, vm_name, interface_name

$vm = $vms | Where-Object -Property Id -eq $nic.VirtualMachine.id 

$ReportDetails.vm_name = $vm.Name 
$ReportDetails.ip-address = [String]$nic.IpConfigurations.PrivateIpAddress
$ReportDetails.interface_name = $nic.Name 
$report += $ReportDetails 

}

$report | Sort-Object VMName | Format-Table ip-address, vm_name, interface_name
$report | Export-Csv -NoTypeInformation -Path $reportFile

}

csv 並非旨在支持具有多值的屬性(例如數組)。 您可以改用 json:

$report | convertto-json | set-content -path $reportFile

或者,如果它必須是 csv,您可以展平結構或將數組連接到分隔字符串,例如

$ReportDetails.ip-address = ($nic.IpConfigurations.PrivateIpAddress -join "|")

作為一般建議,您應該盡量避免使用遞增賦值運算符 ( += ) 創建集合,此外$null` 應該位於相等比較的左側

對於相關腳本和擴展ip_address屬性,這意味着:

# Get all the VMs from the selected subscription
$vms = Get-AzVM

# Get all the Network Interfaces
$nics = Get-AzNetworkInterface | Where-Object { $Null -ne $_.VirtualMachine } 

$ReportDetails = foreach ($nic in $nics) {
    $vm = $vms | Where-Object -Property Id -eq $nic.VirtualMachine.id 
    $nic.IpConfigurations.PrivateIpAddress.foreach{
        [PSCustomObject]@{
            vm_name = $vm.Name 
            ip_address = $_
            interface_name = $nic.Name
        }
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM