Tag Archive for: Program

Advanced Network Diagnostics Tool

Description:

This PowerShell script creates a simple network diagnostics tool. It allows users to perform basic network troubleshooting tasks such as pinging a host, checking DNS resolution, viewing network adapter information, and performing a traceroute. The script demonstrates working with network-related cmdlets, handling user input, and presenting network information in a readable format.

Full Script:

# Advanced Network Diagnostics Tool

# Function to display the menu
function Show-Menu {
    Clear-Host
    Write-Host "=== Advanced Network Diagnostics Tool ===" -ForegroundColor Cyan
    Write-Host "1.  Ping a host"
    Write-Host "2.  Resolve DNS"
    Write-Host "3.  View network adapter information"
    Write-Host "4.  Perform traceroute"
    Write-Host "5.  View open ports"
    Write-Host "6.  Check internet connectivity"
    Write-Host "7.  View IP configuration"
    Write-Host "8.  Perform a network speed test"
    Write-Host "9.  Flush DNS cache"
    Write-Host "10. View routing table"
    Write-Host "11. Exit"
}

# Function to ping a host
function Ping-Host {
    $host_name = Read-Host "Enter the host name or IP address to ping"
    Write-Host "`nPinging $host_name..." -ForegroundColor Yellow
    $result = Test-Connection -ComputerName $host_name -Count 4 -ErrorAction SilentlyContinue
    if ($result) {
        $result | Format-Table @{Name="Source"; Expression={$_.PSComputerName}}, 
                               @{Name="Destination"; Expression={$_.Address}}, 
                               @{Name="IPV4Address"; Expression={$_.IPV4Address}}, 
                               ResponseTime
    } else {
        Write-Host "Unable to reach $host_name" -ForegroundColor Red
    }
}

# Function to resolve DNS
function Resolve-DNSName {
    $dns_name = Read-Host "Enter the domain name to resolve"
    Write-Host "`nResolving $dns_name..." -ForegroundColor Yellow
    try {
        $result = Resolve-DnsName -Name $dns_name -ErrorAction Stop
        $result | Format-Table Name, IPAddress
    } catch {
        Write-Host "Unable to resolve $dns_name. Error: $($_.Exception.Message)" -ForegroundColor Red
    }
}

# Function to view network adapter information
function View-NetworkAdapters {
    Write-Host "`nNetwork Adapter Information:" -ForegroundColor Yellow
    Get-NetAdapter | Where-Object Status -eq "Up" | Format-Table Name, InterfaceDescription, Status, LinkSpeed
}

# Function to perform traceroute
function Perform-Traceroute {
    $destination = Read-Host "Enter the destination for traceroute"
    Write-Host "`nPerforming traceroute to $destination..." -ForegroundColor Yellow
    Test-NetConnection -ComputerName $destination -TraceRoute | 
        Select-Object -ExpandProperty TraceRoute | 
        ForEach-Object { Write-Host $_ }
}

# Function to view open ports
function View-OpenPorts {
    Write-Host "`nViewing open ports..." -ForegroundColor Yellow
    Get-NetTCPConnection | Where-Object State -eq "Established" | 
        Format-Table LocalAddress, LocalPort, RemoteAddress, RemotePort, State
}

# Function to check internet connectivity
function Check-InternetConnectivity {
    Write-Host "`nChecking internet connectivity..." -ForegroundColor Yellow
    $testResult = Test-NetConnection -ComputerName "www.google.com" -InformationLevel "Detailed"
    if ($testResult.TcpTestSucceeded) {
        Write-Host "Internet is accessible." -ForegroundColor Green
    } else {
        Write-Host "Internet is not accessible." -ForegroundColor Red
    }
    $testResult | Format-List
}

# Function to view IP configuration
function View-IPConfiguration {
    Write-Host "`nIP Configuration:" -ForegroundColor Yellow
    Get-NetIPConfiguration | Format-List InterfaceAlias, IPv4Address, IPv6Address, DNSServer
}

# Function to perform a network speed test
function Perform-SpeedTest {
    Write-Host "`nPerforming network speed test..." -ForegroundColor Yellow
    # Note: This requires the installation of speedtest-cli
    # You can install it using: winget install Ookla.Speedtest.CLI
    try {
        $result = speedtest --format=json --progress=no | ConvertFrom-Json
        Write-Host "Download Speed: $([math]::Round($result.download.bandwidth / 125000, 2)) Mbps"
        Write-Host "Upload Speed: $([math]::Round($result.upload.bandwidth / 125000, 2)) Mbps"
        Write-Host "Ping: $($result.ping.latency) ms"
    } catch {
        Write-Host "Unable to perform speed test. Make sure speedtest-cli is installed." -ForegroundColor Red
    }
}

# Function to flush DNS cache
function Flush-DNSCache {
    Write-Host "`nFlushing DNS cache..." -ForegroundColor Yellow
    Clear-DnsClientCache
    Write-Host "DNS cache flushed successfully." -ForegroundColor Green
}

# Function to view routing table
function View-RoutingTable {
    Write-Host "`nRouting Table:" -ForegroundColor Yellow
    Get-NetRoute | Format-Table DestinationPrefix, NextHop, RouteMetric, ifIndex
}

# Main program loop
do {
    Show-Menu
    $choice = Read-Host "`nEnter your choice (1-11)"

    switch ($choice) {
        "1"  { Ping-Host }
        "2"  { Resolve-DNSName }
        "3"  { View-NetworkAdapters }
        "4"  { Perform-Traceroute }
        "5"  { View-OpenPorts }
        "6"  { Check-InternetConnectivity }
        "7"  { View-IPConfiguration }
        "8"  { Perform-SpeedTest }
        "9"  { Flush-DNSCache }
        "10" { View-RoutingTable }
        "11" { Write-Host "Exiting program..." -ForegroundColor Yellow; break }
        default { Write-Host "Invalid choice. Please try again." -ForegroundColor Red }
    }

    if ($choice -ne "11") {
        Read-Host "`nPress Enter to continue..."
    }
} while ($choice -ne "11")

This advanced Network Diagnostics Tool includes:

  1. A comprehensive menu with 11 options
  2. Functions for various network diagnostic tasks:
    • Pinging a host
    • Resolving DNS names
    • Viewing network adapter information
    • Performing a traceroute
    • Viewing open ports
    • Checking internet connectivity
    • Viewing IP configuration
    • Performing a network speed test (requires speedtest-cli)
    • Flushing DNS cache
    • Viewing the routing table
  3. Use of various PowerShell cmdlets related to networking
  4. Error handling for network operations
  5. Formatting of output for better readability

This script provides a more comprehensive set of tools for network diagnostics and troubleshooting. It’s suitable for users who want to perform a wider range of network-related tasks and gain more detailed insights into their network configuration and performance.

Note: The speed test function requires the installation of speedtest-cli, which can be installed using the Windows Package Manager (winget) or downloaded from the Ookla website.

Task Manager and Process Monitor

Description:

This PowerShell script creates a simple task manager and process monitor. It allows users to view running processes, sort them by various criteria, and perform basic actions like stopping a process. The script demonstrates working with processes, user input handling, and basic data manipulation in PowerShell.

Full Script:

# Task Manager and Process Monitor

# Function to display the menu
function Show-Menu {
    Clear-Host
    Write-Host "=== Task Manager and Process Monitor ===" -ForegroundColor Cyan
    Write-Host "1. View all running processes"
    Write-Host "2. View top 10 processes by CPU usage"
    Write-Host "3. View top 10 processes by Memory usage"
    Write-Host "4. Search for a process"
    Write-Host "5. Stop a process"
    Write-Host "6. Exit"
}

# Function to view all running processes
function View-AllProcesses {
    Get-Process | Format-Table Id, ProcessName, CPU, WorkingSet -AutoSize
}

# Function to view top 10 processes by CPU usage
function View-TopCPUProcesses {
    Get-Process | Sort-Object CPU -Descending | Select-Object -First 10 | 
        Format-Table Id, ProcessName, CPU -AutoSize
}

# Function to view top 10 processes by Memory usage
function View-TopMemoryProcesses {
    Get-Process | Sort-Object WorkingSet -Descending | Select-Object -First 10 | 
        Format-Table Id, ProcessName, @{Name="Memory (MB)"; Expression={[math]::Round($_.WorkingSet / 1MB, 2)}} -AutoSize
}

# Function to search for a process
function Search-Process {
    $searchTerm = Read-Host "Enter process name to search"
    Get-Process | Where-Object {$_.ProcessName -like "*$searchTerm*"} | 
        Format-Table Id, ProcessName, CPU, WorkingSet -AutoSize
}

# Function to stop a process
function Stop-UserProcess {
    $processId = Read-Host "Enter the Process ID to stop"
    try {
        Stop-Process -Id $processId -Force -ErrorAction Stop
        Write-Host "Process with ID $processId has been stopped." -ForegroundColor Green
    }
    catch {
        Write-Host "Error: Unable to stop process. $($_.Exception.Message)" -ForegroundColor Red
    }
}

# Main program loop
do {
    Show-Menu
    $choice = Read-Host "`nEnter your choice (1-6)"

    switch ($choice) {
        "1" { View-AllProcesses }
        "2" { View-TopCPUProcesses }
        "3" { View-TopMemoryProcesses }
        "4" { Search-Process }
        "5" { Stop-UserProcess }
        "6" { Write-Host "Exiting program..." -ForegroundColor Yellow; break }
        default { Write-Host "Invalid choice. Please try again." -ForegroundColor Red }
    }

    if ($choice -ne "6") {
        Read-Host "`nPress Enter to continue..."
    }
} while ($choice -ne "6")

This script includes:

  1. A menu display function for user interaction
  2. Functions to view all processes, top CPU-consuming processes, and top memory-consuming processes
  3. A function to search for processes by name
  4. A function to stop a process by its ID
  5. Use of PowerShell cmdlets like Get-Process, Stop-Process, and Format-Table
  6. Sorting and filtering of process data
  7. Basic error handling when stopping a process
  8. Formatting of output for better readability

The script provides a simple interface for users to monitor and manage system processes, making it suitable for beginners to understand PowerShell scripting concepts, process management, and data manipulation. It also introduces concepts like error handling and custom formatting of output data.

System Information Gatherer

Description:

This PowerShell script is designed for beginners to learn how to gather and display basic system information. It demonstrates how to use various PowerShell cmdlets to retrieve information about the computer’s hardware, operating system, and current user. The script also introduces basic formatting techniques to present the information in a readable manner.

Full Script:

# System Information Gatherer

# Function to get and display system information
function Get-SystemInfo {
    Clear-Host
    Write-Host "=== System Information Gatherer ===" -ForegroundColor Cyan

    # Get computer system information
    $computerSystem = Get-CimInstance CIM_ComputerSystem
    $operatingSystem = Get-CimInstance CIM_OperatingSystem

    # Display basic system information
    Write-Host "`nComputer Name: " -NoNewline -ForegroundColor Yellow
    Write-Host $computerSystem.Name

    Write-Host "Manufacturer: " -NoNewline -ForegroundColor Yellow
    Write-Host $computerSystem.Manufacturer

    Write-Host "Model: " -NoNewline -ForegroundColor Yellow
    Write-Host $computerSystem.Model

    Write-Host "Operating System: " -NoNewline -ForegroundColor Yellow
    Write-Host $operatingSystem.Caption

    Write-Host "OS Version: " -NoNewline -ForegroundColor Yellow
    Write-Host $operatingSystem.Version

    # Get and display CPU information
    $processor = Get-CimInstance CIM_Processor
    Write-Host "`nCPU Information:" -ForegroundColor Green
    Write-Host "Name: $($processor.Name)"
    Write-Host "Cores: $($processor.NumberOfCores)"
    Write-Host "Logical Processors: $($processor.NumberOfLogicalProcessors)"

    # Get and display memory information
    $totalMemory = [math]::Round($computerSystem.TotalPhysicalMemory / 1GB, 2)
    Write-Host "`nMemory Information:" -ForegroundColor Green
    Write-Host "Total Physical Memory: $totalMemory GB"

    # Get and display disk information
    Write-Host "`nDisk Information:" -ForegroundColor Green
    Get-CimInstance CIM_LogicalDisk | Where-Object {$_.DriveType -eq 3} | ForEach-Object {
        $freeSpace = [math]::Round($_.FreeSpace / 1GB, 2)
        $totalSize = [math]::Round($_.Size / 1GB, 2)
        Write-Host "Drive $($_.DeviceID): $freeSpace GB free of $totalSize GB"
    }

    # Get and display current user information
    $currentUser = [System.Security.Principal.WindowsIdentity]::GetCurrent()
    Write-Host "`nCurrent User Information:" -ForegroundColor Green
    Write-Host "Username: $($currentUser.Name)"
}

# Main program
Get-SystemInfo

# Pause to keep the console window open
Read-Host "`nPress Enter to exit..."

This script includes:

  1. A function Get-SystemInfo that gathers and displays various system information
  2. Use of PowerShell cmdlets like Get-CimInstance to retrieve system data
  3. Formatting techniques to make the output more readable (colors, alignment)
  4. Basic math operations to convert bytes to gigabytes
  5. Use of pipeline and Where-Object for filtering disk information
  6. Retrieval of current user information

The script provides a comprehensive overview of the system’s hardware and software configuration, making it useful for beginners to understand how to access and present system information using PowerShell. It also introduces concepts like working with CIM instances, formatting output, and basic data manipulation.