r/PowerShell • • Jun 16 '21

'ipconfig /all' - Posh version

Another of my - 'Not sure how useful this is but...'

I wanted a more comprehensive, and easier to read, output of a systems network settings, etc...

An image of what the output looks like is shown here: http://www.somethingtoscrollthrough.com/2021/06/ipconfig-all-posh-version.html

This is set-up as a Function, and it has an alias.

I call these functions from both PoSh profiles (ISE and Console).

Here is the code:

https://github.com/richie65x/Modules/blob/main/Get-IP.psm1

Function Get-IP {

Write-Host "Fetching IP info..." -ForegroundColor Gray -BackgroundColor Black
$AdapterList = @()
Get-NetAdapter | ? {$_.InterfaceDescription -NOTmatch 'Bluetooth'}  | % { 
$adapter = $_
$prefix = (Get-NetIPAddress -InterfaceIndex $adapter.InterfaceIndex | ? {$_.ipv4address}).prefixlength
('1' * $prefix).PadRight(32, '0') | Out-Null;$bitString=('1' * $prefix).PadRight(32,'0'); $SnM=[String]::Empty
    for($i=0;$i -lt 32;$i+=8)
    {$byteString=$bitString.Substring($i,8); $SnM+="$([Convert]::ToInt32($byteString, 2))."}
If ((Get-NetIPInterface -InterfaceAlias $_.InterfaceAlias).Dhcp -eq "Enabled") {$DHCP = "DHCP"} else {$DHCP = "STATIC"}
$AdapterList += ((Get-NetIPConfiguration | ? {$_.InterfaceIndex -match "$($adapter.InterfaceIndex)"} | select `
    @{Name='Alias';Expression ={$_.InterfaceAlias}},`
    @{Name='Status';Expression ={$_.NetAdapter.Status}},`
    @{Name='IPAddress';Expression ={"$($_.IPv4Address.IPAddress) ($DHCP)"}},`
    @{Name='SubnetMask';Expression ={"$($SnM.TrimEnd('.')) (/$prefix)"}},`
    @{Name='Gateway';Expression ={$_.IPv4DefaultGateway.NextHop}},`
    @{Name='DNSServer(s)';Expression ={$_.DNSServer.ServerAddresses}},`
    @{Name='MAC';Expression ={$adapter.MacAddress}},`
    @{Name='Index';Expression ={$_.InterfaceIndex}},`
    @{Name='Description';Expression ={$_.InterfaceDescription}}))
    }
Write-Host "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~" -ForegroundColor Gray
$AdapterList | % {
$_ | % {
If ($_.IPAddress -match "169.") {
    $_.IPAddress = "($DHCP)"
    $_.SubnetMask = " - "
}

$Item00 = $_
($Item00 | Out-String).Split("`n|`r",[System.StringSplitOptions]::RemoveEmptyEntries) | % {
If ($Item00.Status -match "Disconnected") {Write-Host "█ " -fore Red -No }
If ($Item00.Status -match "Up") {Write-Host "¤ " -fore Green -No }
If ($_ -match "Index") {Write-Host " " $_ -ForegroundColor cyan} 
If ($_ -match "Alias") {Write-Host " " $_ -ForegroundColor Yellow} 
If ($_ -match ": Up") {Write-Host " " $_ -ForegroundColor Green} 
If ($_ -match ": Disconnected") {Write-Host " " $_ -ForegroundColor Magenta}
If ($_ -NOTmatch "Index" -and $_ -NOTmatch "Alias" -and $_ -NOTmatch "Status") {Write-Host " " $_} 
}

($Item00 | Out-String).Split("`n|`r",[System.StringSplitOptions]::RemoveEmptyEntries) | % {
    If ($_ -match "Alias" -and $_ -match "Wi-Fi" -and $Item00.Status -match "Up") {
        netsh wlan show interfaces | % {
            If ($_ -match "SSID" -and $_ -NOTmatch "BSSID") {$SSID = $_}
            If ($_ -match "State") {$State = $_}
            If ($_ -match "Signal") {$Signal = $_}
            If ($_ -match "Authentication") {$Auth = $_}
        }
            Function SplitWrite($arg0) {Write-Host ($arg0.Split(':')[1]).Trim() -Fore 11}
                Write-Host "             SSID: " -Fore 14 -No; SplitWrite $SSID
                Write-Host "            State: " -Fore 14 -No; SplitWrite $State
                Write-Host "           Signal: " -Fore 14 -No; SplitWrite $Signal
                Write-Host "             Auth: " -Fore 14 -No; SplitWrite $Auth
    } 
}

}
Write-Host "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~" -ForegroundColor Gray
}

} # End Function Get-IP

set-alias -name gip -value Get-IP
127 Upvotes

45 comments sorted by

17

u/Thotaz Jun 16 '21

The problem with custom information gathering tools is that you are typically running them on other computers that don't have your module/profile. That means your tool needs to save a lot of time/effort to be worth the effort of installing it on the other computer.

This looks good to me but I can't imagine many people will use it as long as it's not a built-in command.

On a side note you should consider using other data sources because your function took 3.9 seconds to run on my machine in a fresh Powershell session while "ipconfig /all" only took 34ms in another fresh PS session.

7

u/richie65 Jun 17 '21

I use it with invoke-expression, pointing at the raw git, inside of a(n) invoke-command, to use it on remote systems. Push the function, and then call it.

I do this fairly often.

4

u/darkspark_pcn Jun 17 '21

I haven't heard of this, how do you do this? Is it a fairly simple command, or is it lengthy?

3

u/UsuiRich Jun 17 '21 edited Jun 18 '21

Invoke-Command -ComputerName <hostname> {
Invoke-Expression ((New-Object System.Net.WebClient).DownloadString('https://raw.githubusercontent.com/richie65x/Modules/main/Get-IP.psm1'))
Get-IP
}

1

u/Lee_Dailey [grin] Jun 19 '21

howdy UsuiRich,

it looks like you used the New.Reddit Inline Code button. it's [sometimes] 5th from the left & looks like </>.

there are a few problems with that ...

  • it's the wrong format [grin]
    the inline code format is for [gasp! arg!] code that is inline with regular text.

  • on Old.Reddit.com, inline code formatted text does NOT line wrap, nor does it side-scroll.

  • on New.Reddit it shows up in that nasty magenta text color

for long-ish single lines OR for multiline code, please, use the ...

Code
Block

... button. it's [sometimes] the 12th one from the left & looks like an uppercase T in the upper left corner of a square.

that will give you fully functional code formatting that works on both New.Reddit and Old.Reddit ... and aint that fugly magenta color. [grin]

take care,
lee

0

u/[deleted] Jun 17 '21

[deleted]

2

u/UsuiRich Jun 18 '21

Yeah - I will only invoke stuff from my own Repo - Otherwise, I'mma read every line of the script, before I will run it.

18

u/BlackV Jun 16 '21 edited Jun 16 '21

so... get-netipconfiguration isnt that already doing what this does?

7

u/richie65 Jun 16 '21

Not really... Maybe run this, then run that command, and you'll see the difference.

9

u/BlackV Jun 16 '21 edited Jun 16 '21

I did, and got the errors posted but the output was mostly identical (save the MAC address and the CIDR notation)

1

u/richie65 Jun 17 '21

Nope.

2

u/BlackV Jun 18 '21 edited Jun 18 '21
Get-NetIPConfiguration -All -Detailed

ComputerName                          : DESKTOP-PLKLSUD
InterfaceAlias                        : Ethernet
InterfaceIndex                        : 13
InterfaceDescription                  : Realtek Gaming GbE Family Controller
NetCompartment.CompartmentId          : 1
NetCompartment.CompartmentDescription : Default Compartment
NetAdapter.LinkLayerAddress           : B4-2E-99-EF-EE-A1
NetAdapter.Status                     : Up
NetProfile.Name                       : Network 2
NetProfile.NetworkCategory            : Private
NetProfile.IPv6Connectivity           : Internet
NetProfile.IPv4Connectivity           : Internet
IPv6Address                           : 2406:e003:1036:8401:10f:8e0e:1e7e:e4b8
IPv6TemporaryAddress                  : 2406:e003:1036:8401:b955:ed81:8577:c341
IPv6LinkLocalAddress                  : fe80::10f:8e0e:1e7e:e4b8%13
IPv4Address                           : 192.168.178.116
IPv6DefaultGateway                    : fe80::c225:6ff:fef2:95f0
IPv4DefaultGateway                    : 192.168.178.1
NetIPv6Interface.NlMTU                : 1492
NetIPv4Interface.NlMTU                : 1500
NetIPv6Interface.DHCP                 : Enabled
NetIPv4Interface.DHCP                 : Enabled
DNSServer                             : fd00::c225:6ff:fef2:95f0
                                        fd00::c225:6ff:fef2:95f0
                                        192.168.178.1


get-ip
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
¤   Alias        : Ethernet
¤   Status       : Up
¤   IPAddress    : 192.168.178.116 (DHCP)
¤   SubnetMask   : 255.255.255.0 (/24)
¤   Gateway      : 192.168.178.1
¤   DNSServer(s) : {fd00::c225:6ff:fef2:95f0, fd00::c225:6ff:fef2:95f0, 192.168.178.1}
¤   MAC          : B4-2E-99-EF-EE-A1
¤   Index        : 13
¤   Description  : Realtek Gaming GbE Family Controller
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

so the only difference I can see is

  • Get-NetIPConfiguration - No Subnet shown (I like your idea)

  • Get-IP - No IP v6 details returned

  • Get-IP - No network profile returned

  • Get-IP - has colour

  • Get-IP- Dosnt return an object

  • Get-IP- just needs some error handling updates

2

u/richie65 Jun 18 '21

Thanks for the feedback!
I left out the IPv6 stuff - Because it really has no practical applications inside of a private network...
I won't set up a network for IPv6... Everything is IPv4... I don't block IPv6, but I don't hand out IPv6 addresses, because there is no reason to do so.
The network profile details (at least in all of the environments I have ever worked in) of any pertinence, is there... 'Alias'. None of the other info is useful... "Internet"? - I already know that.
I don't know how to return an object that includes the colorful output I rely on, to allow certain details to stand out.

I'm not really that good at error handling, other than to throw known errant info at the script, and see how it behaves, then accounting for THAT behavior.

3

u/BlackV Jun 18 '21

knowing what profile an adapter is on can help when firewall rules are not working (e.g.. a dr recovery excercise the the domain controller comes up on public profile not domain, then no can talk to the domain controller)

i'd create an object, then use that for your write host, coloured output

you could change your function to an advanced function to support -outvairable which would then be able to grab your object, that'd be 1 way, or you cause have 2 functions in the module one that gets the date and spits it out and one that takes that output and makes it easy to read/formats it

next would be to biff it onto gitlab/github and the powershell gallery then people can use install-module or install-script to get it

and personally I'd get rid of the ~~~~~~~~~~~ from the output and just separate each with 1 or 2 blank lines

as for error handling yeah i'd be using try/catch/-erroraction stop/etc to deal with your errors, you use hyper-v or play around with your local adpater to test against your error conditions (adapter with no IP, adpater disabled, adapter with no DNS, etc)
things like if ther is no ip address, is there a reason to check DNS?

look at the [IPAddress] accelerator for you IP object which may or may not remove the need for your subnet tewaking (pad right, pad left, substring conver bytes, etc)

maybe use only get-netipconfiguration in your script rather than a get-netipaddress then another call again to get-netipconfiguration save getting the same information multiple times

you have a rather large IF that could probably be swapped out for a switch ($x)

a [PSCustomobject] and add-member could be combined to streamline some of the object creation allowing you to maybe easier look at your output

2

u/BlackV Jun 18 '21

Yeah fair enough on the IPv6 stuff

2

u/richie65 Jun 18 '21

The other difference... But you wont see it unless it is run on a system that is connected to Wi-Fi...
This thing lists the SSID, Signal strength, what type of Auth, and the connection state.

Really - Probably SSID, Signal strength are what I rely on ('State' is redundant at that point).
I added those, so I can audit Wi-Fi AP signal throughout the plants (we have three, the one my office is in -in Ohio, one about 6 miles away, and one Virginia)

I'll have to mess around with the methods you suggested - I haven't used them before.

2

u/BlackV Jun 18 '21

Signal strength nice, didn't notices that

5

u/BlackV Jun 16 '21

testing I get the following uncaught errors

Get-NetIPAddress:
Line |
7 |  $prefix = (Get-NetIPAddress -InterfaceIndex $adapter.InterfaceIndex | …
    | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    | No MSFT_NetIPAddress objects found with property 'InterfaceIndex' equal to '25'.  Verify the value of the property and retry.
    Get-NetIPInterface:
    Line |
    11 |  If ((Get-NetIPInterface -InterfaceAlias $_.InterfaceAlias).Dhcp -eq " …
    |       ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    | No MSFT_NetIPInterface objects found with property 'InterfaceAlias' equal to 'Wi-Fi'.  Verify the value of the property and retry.
Get-NetIPAddress:
Line |
7 |  $prefix = (Get-NetIPAddress -InterfaceIndex $adapter.InterfaceIndex | …
    |             ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    | No MSFT_NetIPAddress objects found with property 'InterfaceIndex' equal to '20'.  Verify the value of the property and retry.
Get-NetIPInterface:
Line |
11 |  If ((Get-NetIPInterface -InterfaceAlias $_.InterfaceAlias).Dhcp -eq " …
        | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
        | No MSFT_NetIPInterface objects found with property 'InterfaceAlias' equal to 'Network Bridge'.  Verify the value of the property and retry.
        Get-NetIPAddress:
        Line |
        7 |  $prefix = (Get-NetIPAddress -InterfaceIndex $adapter.InterfaceIndex | …
            | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
            | No MSFT_NetIPAddress objects found with property 'InterfaceIndex' equal to '6'.  Verify the value of the property and retry.
            Get-NetIPInterface:
            Line |
            11 |  If ((Get-NetIPInterface -InterfaceAlias $_.InterfaceAlias).Dhcp -eq " …
    |       ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    | No MSFT_NetIPInterface objects found with property 'InterfaceAlias' equal to 'Ethernet'.  Verify the value of the property and retry.

adapters that are possibly disabled, adapters that do not have an IP or have Set-NetIPInterface -Dhcp Disabled configured or virtual adapters or adpaters that are on a VM switch

2

u/richie65 Jun 18 '21

Maybe try: $ErrorActionPreference = "SilentlyContinue"

What do you see when you run this?:
Get-NetAdapter | ? {$_.InterfaceDescription -NOTmatch 'Bluetooth'}

The script is doing a For-Each on the results of that command.

10

u/EIGRP_OH Jun 16 '21

Awesome! Really like the idea of highlighting key values that are mostly looked at it. As many times as I’ve done ipconfig /all it still takes me a few seconds to locate what I’m looking for. With this the color will catch my eye

-4

u/Burning_Ranger Jun 17 '21

Yes... But how long will it take to download and install this module?

4

u/richie65 Jun 17 '21

I currently have a total of 9 modules, as well as a highly customized prompt, and color schema. It takes about 0.63 seconds to load the profile, and another 1.5 seconds to load, if I'm also calling the Active Directory module too... But I leave my PoSh sessions open for days.

6

u/cheffromspace Jun 17 '21

If only there were a scripting tool that could automate that.

39

u/Th3Sh4d0wKn0ws Jun 16 '21
Get-NetAdapter -Physical | Get-NetIPConfiguration

I say that, but I also totally appreciate what you did here and think it looks really good. I think it was worthwhile, and thanks for sharing.

3

u/UsuiRich Jun 17 '21

Get-NetAdapter -Physical | Get-NetIPConfiguration

That is nice, because of it's brevity - But...
This thing I put together provides a great deal more information than that command does.
That was the intent, more details, and readability.

3

u/BlackV Jun 18 '21

see -All and -Detailed paramaters

8

u/pertymoose Jun 17 '21

Aaactually, this is a Write function, not a Get function.

A Get function returns data, hence the verb, whereas a Write function prints information to the console.

1

u/BergerLangevin Jun 17 '21

Is your script return everything as an 1 object?

1

u/richie65 Jun 17 '21

No... But it could... Though, it's visual elements would be lost.

3

u/vermyx Jun 17 '21

When handling this type of scenario, I personally create one function that creates the object and one that displays it, and the display just call the object creation function. You can have it as one function and just use flags to indicate whether to display and/or return an object

0

u/[deleted] Jun 17 '21

[deleted]

0

u/richie65 Jun 17 '21

If you are dealing with an array (for example), but for whatever reason, want to work work with it as a string, that is how you cast it to a string.
You would want to research it further, on your own, in order to get a better picture.

3

u/arniom Jun 16 '21

Some month ago I saw this, with an ipconfig example. https://devblogs.microsoft.com/powershell/announcing-powershell-crescendo-preview-1

Also, searching the previous link I saw there's a new preview since last month https://devblogs.microsoft.com/powershell/announcing-powershell-crescendo-preview-2/

1

u/BlackV Jun 18 '21

Yeah I have No idea what makes cresendo useful

you can do all this already with existing powsershell function (acting as a proxy and formatter for ipconfig output)
you have already convert from string and convert from string with templates

I need more use cases I think

3

u/cheffromspace Jun 17 '21

Nice. I have a job monitoring script who's output could really use some formatting but I've just been too lazy to do it. This gives me some inspiration.

1

u/Burning_Ranger Jun 17 '21

It's a good step in learning powershell, but have to agree with the other response that it's not particularly useful because who's going to install a powershell module just to get the ip information in a more clear and easy to read manner for each and every pc they want to run this for when ipconfig /all does the same thing.

You could improve it by making it a advanced function that you can pass multiple computer host names to and have to query each machine remotely.

1

u/UsuiRich Jun 17 '21 edited Jun 18 '21

For anyone curious as to how to run this on a remote session - There are several ways - Below is just a method for invoking it via GitHub...But it can also be removed from its 'Function' brackets, thus invoking it as just a straight up script...Anyway - Here is how to call it as a remote command, and call it from a git repo:

Invoke-Command -ComputerName <hostname> {
Invoke-Expression ((New-Object System.Net.WebClient).DownloadString('https://raw.githubusercontent.com/richie65x/Modules/main/Get-IP.psm1')) Get-IP }

1

u/lcpittman2020 Jun 17 '21

Nice! Great job!

1

u/kcooper71194 Jun 17 '21

I never saved a post so quickly lol

1

u/HenrikHDK Jun 17 '21

Great idea and initiative. Thanks for this.

0

u/[deleted] Jun 17 '21

While I can appreciate the effort here.. I'd never user this. :)

-3

u/wattsdp Jun 16 '21

One thing your output is missing is the Mac address of the interface. It looks great. And I am reasonably sure that attribute can be added in quickly.

4

u/richie65 Jun 16 '21

I'm not sure what could be missing... This script absolutely shows the MAC.

1

u/j0hnnyrico Jun 16 '21

I second this. Gj!

3

u/wattsdp Jun 17 '21

This is what happens when I scour through reddit early in the morning. I miss simple things like the blurred output showing the MAC. My bad