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:
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
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}}