Basic Scripting with PowerShell
With basic PowerShell commands covered, the next step is to write and run a script for more complex actions.
For this we use the PowerShell ISE (the PowerShell text editor). The scenario: given a list of port numbers, check whether each local port is listening. Open the listening-ports.ps1 script on the Desktop with the PowerShell ISE. PowerShell scripts usually carry the .ps1 extension.
$system_ports = Get-NetTCPConnection -State Listen
$text_port = Get-Content -Path C:\Users\Administrator\Desktop\ports.txt
foreach($port in $text_port){
if($port -in $system_ports.LocalPort){
echo $port
}
}
How the Script Works
The first line gets every port on the system that is listening, using the Get-NetTCPConnection cmdlet, and stores the output in a variable. The convention for creating a variable is:
$variable_name = value
The next line reads the list of ports from the file with the Get-Content cmdlet, again storing the output in a variable. From there, iterate through the ports in the file to check which are listening:
foreach($new_var in $existing_var){}
This block loops through a set of objects. For each port, check whether it appears in the listening local ports. Rather than a second for loop, use an if statement with the -in operator to test whether the port exists in the LocalPort property of any object. A full list of if statement comparison operators can be found here. To run the script, call the script path from PowerShell or click the green button in the PowerShell ISE:
Your Turn
Now it is time to write one of your own. The emails folder on the Desktop holds copies of the emails John, Martha, and Mary have been sending to each other (and themselves). Answer the questions about these emails with a script rather than opening the files.
Scripting can be a bit difficult, but here is a good resource to use: