A piece of software we work with outputs a JSON stream with the status of the software (if it's running on master or slave for example).
I'm using powershell to get this data, and from there I'll be either posting it to a database or something else, but that's not really relevant to this particular question.
I come from a web developer background so I'm familiar with conditional statements, variables etc. in PHP. However it appears to work differently for PowerShell by the looks of it. I'm pretty new to Powershell.
So the premise of the below snippet is that:
- It reads a CSV containing the first three octets of an internal IP address (with the header IP) and the name of the location (with the header SITE).
- Runs a foreach loop on the contents of the CSV and then runs conditional statement to first determine if the machine(s) are online using TEST-CONNECTION.
- If the primary/master is online, display it's status, otherwise check the secondary/slave and display it's status, or if both are offline (the first two are taken from the JSON feed) simply display All Offline
- At the end of each foreach, to simply write-host the variable $status
Currently it disregards the IF/ELSEIF/ELSE and just shows System Offline. Any ideas?
$sites = Import-CSV 'D:\Batch Files\fb.csv'
Foreach ($item in $sites) {
$ip = $($item.IP)
$primary = '$ip.205'
$secondary = '$ip.210'
$site = $($item.SITE)
If (Test-Connection $primary -count 2 -quiet) {
$request = 'http://' + $primary + ':32768/Console/SystemStatus.json'
Invoke-WebRequest $request | ConvertFrom-Json |select -expand PrimaryServer | select -expand Online -outvariable status
}
Elseif (Test-Connection $secondary -count 2 -quiet) {
$request = 'http://' + $secondary + ':32768/Console/SystemStatus.json'
Invoke-WebRequest $request | ConvertFrom-Json |select -expand SecondaryServer | select -expand Online -outvariable status
}
Else {
$status = 'System Offline'
}
Write-Host $status
}
CSV Contents:
IP,SITE
10.18.21,Name1
10.18.39,Name2
Now if I were to run the below, I do indeed get the correct output for $status however it's also displayed a second time probably due to something I'm missing to hide output from the select/expand.
$primary='10.18.21.205'
If (Test-Connection $primary -count 2 -quiet) {
$request = 'http://' + $primary + ':32768/Console/SystemStatus.json'
Invoke-WebRequest $request | ConvertFrom-Json |select -expand PrimaryServer | select -expand Online -outvariable status
Write-Host $status
}
Thank You