Search code examples
powershellforeachping

Append information to the output of an existing command


A former colleague gave me these two PowerShell scripts to run, log, and monitor a continuous ping test:

Run & Log:

ping.exe -l 1500 -t W2K16svr|Foreach{"{0} - {1}" -f (Get-Date),$_} | out-file C:\Temp\PingTest.txt -Encoding UTF8

Monitor (in another PS instance):

Get-content C:\Temp\PingTest.txt -tail 10 -wait

This works great, but I need to check a user with a laptop who often has to switch to WiFi, so I need the output to record the connection type (Ethernet or Wifi) so I can exclude the latter.

I've figured out I can get the connection type with this:

get-netconnectionprofile | select -ExpandProperty InterfaceAlias

… but what I can't figure out is how to append that to the ping output. Everything I've tried so far errors out.

Is it possible to do what I want, and if so, how?


Solution

  • You can include the information in the string you're already synthesizing via -f, the format operator:

    "{0} - {1} - {2}" -f (Get-Date), $_, [string] (Get-NetConnectionProfile).InterfaceAlias
    

    Note:

    • The [string] cast ensures that, even if there happen to be multiple connection profiles, only a single string is returned, taking advantage of how PowerShell stringifies arrays, namely by space-concatenating their (stringified) elements (e.g., [string] @('foo', 'bar') becomes 'foo bar').

    • Instead of piping to Select-Object -ExpandProperty, direct property access is performed on the output from Get-NetConnectionProfile, via enclosure in (...). This is more concise and efficient, and even works with multiple output objects, courtesy of PowerShell's member-access enumeration.