Home > OS >  How to join results of two variables in Powershell with a forward slash?
How to join results of two variables in Powershell with a forward slash?

Time:10-12

With this script i am able to get a csv file containing different coulmns like ip address and subnetmask prefix of a vm but i want to have the ip address and the netmask Prefix in this format eg.: 10.1.1.1/26 combined in one coulmn. What is the possible best way to do that. Thanks

connect-AzAccount -Confirm

        # Report Name and location
        $reportFile = "C:\Users\john\Desktop\Inventory\Final Scripts\IP Address Details_$(get-date -f dd.MM.yyyy).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 { $Null -ne $_.VirtualMachine } 
        $ReportDetails = foreach ($nic in $nics) {
        $vnet = Get-AzVirtualNetwork -Name $nic.IpConfigurations.Subnet.Id.Split("/")[-3] 
        $subnet = $nic.IpConfigurations.Subnet.Id.Split("/")[-1]
        $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
        netmask= (Get-AzVirtualNetworkSubnetConfig -VirtualNetwork $vnet -Name $subnet).AddressPrefix.Split("/")[-1]
        

        
    }
}

}

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

CodePudding user response:

assuming $ip_address contains a single IP and $netInfo contains the subnetmask u can use -join "\" to merge the data:

$ip_address = $_
$netmask= (Get-AzVirtualNetworkSubnetConfig -VirtualNetwork $vnet -Name $subnet).AddressPrefix.Split("/")[-1]
$netInfo = $ip_address,$netmask -join "/"

[PSCustomObject]@{
    vm_name = $vm.Name 
    netInfo = $netInfo
    interface_name = $nic.Name
}
  • Related