Elementary Powershell loop with conditions

Elementary Powershell loop with conditions

Loops are a fundamental part of automating repetitive tasks, allowing system administrators to perform repetitive tasks in multiple systems or items sequentially and autonomously. The need to handle or skip possible errors or issues arises , but Powershell has it covered in a couple of easy ways.

The example in this post consists of resolving the task ID to process name, and, IP to the domain used in the background by all the currently runningapplications, and correcting in case of errors. The task involves using the cmdlet Get-NetTCPConnection. The script will also use other cmdlets such as Sort-Object, Get-Process, Select-Object, Resolve-DnsName and Write-Output.

Most loops in Powershell and conditon testing can be handled by the following cmdlet and utility.

ForEach-Object

This allows for operations on each item in a collection of input objects piped to other cmdlets.

if (…) {…} elseif (…){…} else(…){…}

This function conducts a conditional evaluation that returns the expression as true or false, and allowing actions to be performed accordingly.

Lets start by opening the Powershell shell and running the cmdlet Get-NetTCPConnection. The ouput shows/includes several unresolvable remote and local addresses and ports.

We can set a few variables to identify the exceptions to be handled in the script.

The main ForEach-Object loop will get most of the details required to resolve application and domain name.

The first step is to ignore ports and IPs set earlier in the variables.

Create new variables that will resolve the application ID to name, and IP to domain name.

This is a sub-conditional function that will change the output of empty domain names to the statement “No Record”.

Define the output variable to specific variables.

Output the result to the console in a formatted fashion.

The result is below.

The whole code is below.