Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to display TestConnection -Quiet result in PowerShell script?

Get-CIMInstance -ClassName Win32_Printer | Select-Object Name, @{label="IPAddress";expression={($_.comment | Select-string -Pattern "\d{1,3}(\.\d{1,3}){3}" -AllMatches).Matches.value}}, @{label="Status";expression={ForEach-Object{Test-Connection -ComputerName '{0}' $_.IPAddress -Count 1 -Quiet}}}

The above code gives me the following o/p:

Name                          IPAddress       Status
----                          ---------       ------
Webex Document Loader         100.100.100.100
OneNote (Desktop)             111.111.111.111
Microsoft XPS Document Writer 120.120.120.120
Microsoft Print to PDF        123.123.123.123
Fax                           8.8.8.8

When the ForEach-Object{Test-Connection -ComputerName $IPAddress -Count 1 -Quiet} is run separately, I get the following o/p:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

False
False
False
False
True

What I need is:

Name                          IPAddress       Status
----                          ---------       ------
Webex Document Loader         100.100.100.100 False
OneNote (Desktop)             111.111.111.111 False
Microsoft XPS Document Writer 120.120.120.120 False
Microsoft Print to PDF        123.123.123.123 False
Fax                           8.8.8.8         True

How can I achieve this, in a single cmdlet (pipelined) ? Thanks in advance

>Solution :

Remove the ForEach-Object{} statement from the property expression, and then split it into two Select-Object calls – the first one will calculate the IPAddress property value, which the second one can then use for the Status calculation:

Get-CIMInstance -ClassName Win32_Printer | Select-Object Name, @{label="IPAddress";expression={($_.comment | Select-string -Pattern "\d{1,3}(\.\d{1,3}){3}" -AllMatches).Matches.value}} |Select Name,IPAddress,@{label="Status";expression={Test-Connection -ComputerName $_.IPAddress -Count 1 -Quiet}}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading