Read a xlxs table with colums of ip adresses and ports

Hi everyone i am trying to create a script with powershell to read a table that contains ip adresses and ports.
These ip adresses sometimes are in the cidr notation and sometimes normal. So the script have to read them without the cidr notation and sometimes there a many ip adresses in one column seperatet with “,”.
In a other column there are ports some in normal notation like 443 sometimes don’t know why they are juts like this g-25. So the script have to recognize it is port 25.
The problem know is, i have to combine each IP-adress with these ports and test this adress with test-netconnection -Port XX
Next Problem i have no adminrights on the computer so i cant install any modules.
Here my Code that is not really that what it have to do:

# Importiere das Modul
Import-Module ImportExcel

# Pfad zur XLSX-Datei
$pathToFile = "C:\Users\XXXX\Desktop\XXXX - Application_XXXX.xlsx"

# Sicherstellen, dass der Pfad zur Datei korrekt ist
if (-Not (Test-Path $pathToFile)) {
    Write-Host "Die angegebene Datei wurde nicht gefunden: $pathToFile"
    exit
}

# XLSX-Datei einlesen und Fehlerbehandlung hinzufügen
try {
    $excelData = Import-Excel -Path $pathToFile -WorksheetName 'Internet Connectivity Details'
    if ($excelData -eq $null -or $excelData.Count -eq 0) {
        Write-Host "Keine Daten in der Excel-Datei gefunden oder die Datei ist leer."
        exit
    }
    Write-Host "Excel-Datei erfolgreich geladen."
} catch {
    Write-Host "Fehler beim Laden der Excel-Datei: $_"
    exit
}

# Neue Spalte für Ergebnisse hinzufügen
$columnName = 'Result'
$columnExists = $excelData[0].PSObject.Properties.Name -contains $columnName

if (-not $columnExists) {
    Write-Host "Füge neue Spalte '$columnName' hinzu..."
    $excelData | Export-Excel -Path $pathToFile -WorksheetName 'Internet Connectivity Details' -AutoSize
    $package = Open-ExcelPackage -Path $pathToFile
    $worksheet = $package.Workbook.Worksheets['Internet Connectivity Details']
    $worksheet.Cells[1, $worksheet.Dimension.End.Column + 1].Value = $columnName
    Close-ExcelPackage $package
}

# Erstellen eines Arrays zur Speicherung der aktualisierten Daten
$updatedData = @()

foreach ($entry in $excelData) {
    # IP-Adressen oder Hostnamen aus den spezifischen Spalten
    $sources = $entry.'URL of the Site / Configured Source' -split ',' # Spalte B
    $destinations = $entry.'Configured Destination' -split ',' # Spalte C

    # Port oder Dienst aus Spalte D
    $portOrService = $entry.'Port / Configured Service'
    
    # Kombiniere alle IPs und Hostnamen
    $allIPs = $sources + $destinations
    $results = @()

    # Teste jede IP-Adresse oder jeden Hostnamen
    foreach ($ip in $allIPs) {
        $ip = $ip.Trim()  # Entfernt führende oder nachgestellte Leerzeichen

        if ($ip) { # Überprüfen, ob die IP-Adresse oder der Hostname nicht leer ist
            try {
                $port = $null
                if ($portOrService -match '^\d+$') {
                    $port = [int]$portOrService
                }

                $result = if ($port) {
                    # TCP-Verbindungstests mit angegebenem Port
                    Test-NetConnection -ComputerName $ip -Port $port
                } else {
                    # Ping-Test oder andere Verbindungen
                    Test-NetConnection -ComputerName $ip
                }

                $message = "`nTesting IP/Hostname: $ip`n"
                $message += "Ping Test Result:`n"
                $message += "  PingSucceeded: $($result.PingSucceeded)`n"
                $message += "  Address: $($result.Address)`n"
                if ($result.TcpTestSucceeded) {
                    $message += "  TcpTestSucceeded: $($result.TcpTestSucceeded)`n"
                }
                if ($result.PingReplyDetails) {
                    $message += "  RoundTripTime: $($result.PingReplyDetails.RoundTripTime) ms`n"
                }

                $results += $message
            }
            catch {
                $message = "Fehler beim Testen der IP/Hostname: $ip`nError: $_`n"
                $results += $message
            }
        }
    }

    # Erstellen eines neuen Objekts mit den Ergebnissen
    $updatedData += [PSCustomObject]@{
        'URL of the Site / Configured Source' = $entry.'URL of the Site / Configured Source'
        'Configured Destination' = $entry.'Configured Destination'
        'Port / Configured Service' = $entry.'Port / Configured Service'
        'Comment' = $entry.'Comment'
        'Result' = ($results -join "`n")
    }
}

# Temporäre Datei für Excel
$tempFilePath = "C:\Users\SASGERH\Desktop\WHTC - Application_Intake_v1.4_template1_Temp.xlsx"

# Speichern der aktualisierten Daten in eine temporäre Datei
$updatedData | Export-Excel -Path $tempFilePath -WorksheetName 'Internet Connectivity Details' -AutoSize

# Temporäre Datei einlesen
$package = Open-ExcelPackage -Path $tempFilePath
$worksheet = $package.Workbook.Worksheets['Internet Connectivity Details']

# Hinzufügen der Ergebnisse zur neuen Spalte
$row = 2
foreach ($entry in $updatedData) {
    $worksheet.Cells[$row, $worksheet.Dimension.End.Column].Value = $entry.'Result'
    $row++
}

# Speichern und Schließen der Excel-Datei
Close-ExcelPackage $package

# Ersetzen der alten Datei durch die neue
Move-Item -Path $tempFilePath -Destination $pathToFile -Force

Write-Host "Ergebnisse wurden erfolgreich in die Datei geschrieben: $pathToFile"

Maybe someone could help because my powershell skill ends here

Hi, welcome to the forum :wave:

This should just be a case of sanitising your data, then looping over it. I’m using a CSV as an example because I can keep it all in one script.

$csv = @'
"IPAddress","Port"
"192.168.1.99",""
"10.10.10.10","443"
"192.168.1.33/24,192.168.1.44,10.0.50.1/8,10.10.10.123","g-80"
'@

$testData = $csv | ConvertFrom-Csv

foreach ($row in $testData) {
    # Split rows with multiple entries, it doesn't matter if there's only one entry.
    # Replace the CIDR suffix if it exists.
    $IPAddressList = $row.IPAddress -split ',' -replace '\/\d+$'
    # Replace any non-digit characters in the port field.
    $port = $row.Port -replace '\D+'
    # Loop over all the IP addresses in the row:
    foreach ($IPAddress in $IPAddressList) {
        "Testing IP Address: $IPAddress, Port: $port "
    }
}
3 Likes

Shouldn’t an IP address in CIDR notation actually be treated as a range of IP addresses? :thinking:

It can be both, as noted in the article:

The address may denote a specific interface address (including a host identifier, such as 10.0.0.1/8), or it may be the beginning address of an entire network (using a host identifier of 0, as in 10.0.0.0/8 or its equivalent 10/8).

For example:

  • 198.51.100.14/24 represents the IPv4 address 198.51.100.14 and its associated network prefix 198.51.100.0, or equivalently, its subnet mask 255.255.255.0, which has 24 leading 1-bits.
  • the IPv4 block 198.51.100.0/22 represents the 1024 IPv4 addresses from 198.51.100.0 to 198.51.103.255.
1 Like

You’re totally right. :+1:t3: My question was actually meant as food for thought for @Sascha_Gerhard to also consider this possibility. :wink:

Thx so much for trying to help me! I appriciate that.

So i convert the xlxs file to csv and with your code i have to rename the columns or can i say the data is in table C or D or whatever. The next thing is that this script should test each ip adress + port with test-NetConnection {IP-Address} -Port {Port-Number}
Than store the result from this test in a extra file!

Many, many problems and with my little skill i’m on the end of the road

No, that’s not necessary. My code is just an example of how to process the data in your columns.

Where did the code you posted come from? The techniques you used demonstrate some proficiency with PowerShell. At that level, I would expect you to be able to use my examples to modify your existing code.

It is a firewall whitelist

Screenshot 2024-09-05 073800

column A is URL of the Site / Configured Source
column B is Configured Destination
column C is Port