php - Extract specific object from JSON array as a comma separated string via PowerShell

I'm trying to write a basic JSON interpreter in PowerShell for a scheduled external port scanner which outputs open ports via JSON, but I'm having a lot of trouble getting it to display the data as a comma separated string. The reason for the comma separated string is so that it can be passed to my documentation tool to make notes of client networks.
My PHP Code (working fine, just for reference):
<?php
$host = $_SERVER['REMOTE_ADDR'];
$ports = array(
20,
443,
49371
);
echo "[";
foreach ($ports as $port)
{
$connection = @fsockopen($host, $port, $errno, $errstr, 2);
if (is_resource($connection))
{
echo '{' . '"Port":' . $port . ',' . '"status" : "open"' . "},";
fclose($connection);
}
else
{
echo '{' . '"Port":' . $port . ', "status" : "closed"},';
}
} ?> { "result": "done" } ]
Sample HTML Output when invoking that PHP script:
[{"Port":20, "status" : "open"},{"Port":443, "status" : "open"},{"Port":49731, "status" : "closed"}, { "result": "done" } ]
String (as a variable) that I'm trying to achieve in Powershell:
Open Ports = 20, 443
My Powershell code so far:
$Results = invoke-restmethod -uri "https://mywebsite.com/portscan.php"
$OpenPorts = $Results | Where-Object { $_.status -eq "open"} | ConvertFrom-Json
$Message = "Open Ports: $OpenPorts"
Write-host $Message
The error I can't figure out how to resolve:
ConvertFrom-Json : Invalid JSON primitive: .
At line:2 char:64
+ ... = $Results | Where-Object { $_.status -eq "open"} | ConvertFrom-Json
+ ~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [ConvertFrom-Json], ArgumentException
+ FullyQualifiedErrorId : System.ArgumentException,Microsoft.PowerShell.Commands.ConvertFromJsonCommand
Any help would be sincerely appreciated, I'm not familiar with PowerShell and it's doing my head in!
Answer
Solution:
# Invoke-RestMethod automatically parses the JSON result into
# a [pscustomobject] graph.
# In a manner of speaking, *ConvertFrom-Json is built in*.
$Results = Invoke-RestMethod -Uri "https://mywebsite.com/portscan.php"
# Get the objects representing open ports.
# Note: `Where-Object Status -eq open` is the equivalent of:
# `Where-Object { $_.Status -eq 'open' }`
$OpenPorts = $Results | Where-Object Status -eq open
# Synthesize the output string.
$Message = "Open ports = " + ($OpenPorts.Port -join ', ')
# Output (echo) it.
# Output that isn't redirected or captured is *implicitly* echoed in PowerShell.
$Message
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: filter_sanitize_string
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.