Search code examples
powershellhostname

Powershell list with IPAddress, Prefixlength and Computernames


I've write a PS Script, that gives me all IP Addresses and Prefixlength of Servers from a text file. See code:

$cred = Get-Credential
$computers = Get-Content -Path C:\Users\XX_YY\Desktop\test_hostname_file.txt
invoke-command -computername $computers -Credential $cred -scriptblock {get-netipaddress -AddressFamily IPv4 } | where {$_.ipaddress -like "10.*"} | ft -AutoSize IPaddress, prefixlength

This Script gives me the result as a table. But I need the Computernames as well in the table.

have you an idea how I can handle this?

Cheers Sam


Solution

  • Well, I would do it in another way, but to stick to your question:

    You can use the Automatic variable $ENV:ComputerName to get the computer name and add it to the output using a PS Object

    $cred = Get-Credential
    $computers = Get-Content -Path C:\Users\XX_YY\Desktop\test_hostname_file.txt
    
    invoke-command -computername $computers -Credential $cred -scriptblock {
    $IP = get-netipaddress -AddressFamily IPv4 | where {$_.ipaddress -like "10.*"} 
    $Row = "" | Select Computer,IPaddress,prefixlength
    $Row.Computer = $env:COMPUTERNAME
    $Row.IPaddress = $IP.IPaddress
    $Row.prefixlength = $IP.prefixlength
    return $row
    }