
ทำไม Network Engineer ต้องเรียน PowerShell?
ในปี 2026 งาน Network Engineering ไม่ได้จำกัดอยู่แค่การ Login เข้า Switch/Router แล้วพิมพ์ CLI command อีกต่อไป Infrastructure ที่ซับซ้อนขึ้น Server จำนวนมากขึ้น และ Requirement ที่ต้องทำซ้ำหลายครั้ง ทำให้ Automation เป็นทักษะจำเป็น PowerShell คือเครื่องมือที่ดีที่สุดสำหรับ Network Engineer ที่ทำงานกับ Windows Server environment เพราะ:
- Built-in ใน Windows Server ทุกเวอร์ชัน — ไม่ต้องติดตั้งอะไรเพิ่ม พร้อมใช้งานทันที
- มี Cmdlets สำหรับ Networking โดยเฉพาะ — Test-Connection, Test-NetConnection, Get-NetAdapter และอีกมากมาย
- จัดการ Active Directory, DNS, DHCP, Hyper-V ได้ทั้งหมด — ครบจบในที่เดียว
- Remote Management ข้าม Server หลายเครื่อง — รัน Command บน Server 100 เครื่องพร้อมกัน
- SSH Support — ตั้งแต่ PowerShell 7+ รองรับ SSH ทำให้จัดการ Linux/Network device ได้ด้วย
PowerShell Networking Cmdlets พื้นฐาน
Test-Connection — Ping แบบ PowerShell
Test-Connection เป็น cmdlet ที่เทียบเท่ากับคำสั่ง ping แต่ทำได้มากกว่าเยอะ เพราะ Return กลับมาเป็น Object ไม่ใช่แค่ Text ทำให้นำไปประมวลผลต่อได้:
# Ping ปกติ
Test-Connection -ComputerName 192.168.1.1
# Ping หลายเครื่องพร้อมกัน
$servers = @("192.168.1.1", "192.168.1.2", "10.0.0.1", "8.8.8.8")
$servers | ForEach-Object {
$result = Test-Connection -ComputerName $_ -Count 2 -Quiet
[PSCustomObject]@{
Host = $_
Status = if ($result) { "Online" } else { "Offline" }
}
} | Format-Table -AutoSize
# Ping + วัด Latency เฉลี่ย
Test-Connection -ComputerName "google.com" -Count 10 |
Measure-Object -Property Latency -Average -Maximum -Minimum |
Select-Object Average, Maximum, Minimum
# Ping ทุก IP ใน Subnet (Simple network scan)
1..254 | ForEach-Object -Parallel {
$ip = "192.168.1.$_"
if (Test-Connection -ComputerName $ip -Count 1 -Quiet -TimeoutSeconds 1) {
Write-Output "$ip is alive"
}
} -ThrottleLimit 50
Test-NetConnection — Port Check + Traceroute
Test-NetConnection เป็น cmdlet ที่ทรงพลังกว่า ping มาก ทำได้ทั้ง TCP port check, Traceroute, DNS resolution:
# ตรวจสอบว่า Port เปิดไหม
Test-NetConnection -ComputerName 192.168.1.100 -Port 443
Test-NetConnection -ComputerName 192.168.1.100 -Port 3389 # RDP
Test-NetConnection -ComputerName 192.168.1.100 -Port 22 # SSH
# Traceroute
Test-NetConnection -ComputerName google.com -TraceRoute
# ตรวจหลาย Port พร้อมกัน
$ports = @(22, 80, 443, 3389, 5985, 5986)
foreach ($port in $ports) {
$result = Test-NetConnection -ComputerName 192.168.1.100 -Port $port -WarningAction SilentlyContinue
[PSCustomObject]@{
Port = $port
Open = $result.TcpTestSucceeded
}
}
# ตรวจ Service ว่าพร้อมใช้งานไหม
$services = @(
@{Name="Web Server"; Host="web01"; Port=443},
@{Name="Database"; Host="db01"; Port=1433},
@{Name="Mail Server"; Host="mail01"; Port=25}
)
$services | ForEach-Object {
$r = Test-NetConnection -ComputerName $_.Host -Port $_.Port -WarningAction SilentlyContinue
[PSCustomObject]@{
Service = $_.Name
Host = $_.Host
Port = $_.Port
Status = if ($r.TcpTestSucceeded) { "OK" } else { "FAIL" }
}
} | Format-Table -AutoSize
Resolve-DnsName — DNS Lookup
# A Record
Resolve-DnsName -Name "google.com" -Type A
# MX Record (Mail server)
Resolve-DnsName -Name "google.com" -Type MX
# NS Record (Nameserver)
Resolve-DnsName -Name "google.com" -Type NS
# Reverse DNS
Resolve-DnsName -Name "8.8.8.8" -Type PTR
# ใช้ DNS Server เฉพาะ
Resolve-DnsName -Name "example.com" -Server 8.8.8.8
# ตรวจ DNS Propagation (query หลาย DNS server)
$dnsServers = @("8.8.8.8", "1.1.1.1", "208.67.222.222", "9.9.9.9")
$domain = "mysite.com"
$dnsServers | ForEach-Object {
$result = Resolve-DnsName -Name $domain -Server $_ -Type A -ErrorAction SilentlyContinue
[PSCustomObject]@{
DNSServer = $_
IPAddress = ($result | Where-Object {$_.Type -eq 'A'}).IPAddress -join ", "
TTL = ($result | Where-Object {$_.Type -eq 'A'})[0].TTL
}
} | Format-Table -AutoSize
Get-NetAdapter / Get-NetIPAddress — ข้อมูล Network Interface
# ดู Network Adapter ทั้งหมด
Get-NetAdapter | Format-Table Name, Status, LinkSpeed, MacAddress
# ดู IP Address ทั้งหมด
Get-NetIPAddress | Format-Table InterfaceAlias, IPAddress, PrefixLength, AddressFamily
# ดูเฉพาะ IPv4
Get-NetIPAddress -AddressFamily IPv4 | Where-Object {$_.IPAddress -ne "127.0.0.1"} |
Format-Table InterfaceAlias, IPAddress, PrefixLength
# ดู Gateway
Get-NetRoute -DestinationPrefix "0.0.0.0/0" | Format-Table InterfaceAlias, NextHop
# ดู DNS Server ที่ตั้งค่าไว้
Get-DnsClientServerAddress | Where-Object {$_.ServerAddresses} |
Format-Table InterfaceAlias, ServerAddresses
# ดู Adapter Statistics (Speed, Packets, Errors)
Get-NetAdapterStatistics | Format-Table Name, ReceivedBytes, SentBytes, ReceivedUnicastPackets
จัดการ Windows Firewall ด้วย PowerShell
Windows Firewall เป็นสิ่งที่ Network Engineer ต้องจัดการบ่อยมาก PowerShell ช่วยให้ทำได้เร็วกว่า GUI มาก โดยเฉพาะเมื่อต้องทำบน Server หลายเครื่อง:
# ดู Firewall Rules ทั้งหมด
Get-NetFirewallRule | Format-Table DisplayName, Direction, Action, Enabled
# ดูเฉพาะ Rule ที่เปิดอยู่ (Enabled)
Get-NetFirewallRule -Enabled True | Format-Table DisplayName, Direction, Action
# สร้าง Firewall Rule — Allow Inbound Port 8080
New-NetFirewallRule -DisplayName "Allow Web Alt 8080" `
-Direction Inbound -Protocol TCP -LocalPort 8080 `
-Action Allow -Profile Domain,Private
# สร้าง Rule — Allow Ping (ICMP)
New-NetFirewallRule -DisplayName "Allow ICMPv4-In" `
-Protocol ICMPv4 -IcmpType 8 -Direction Inbound -Action Allow
# Block IP range เฉพาะ
New-NetFirewallRule -DisplayName "Block Suspicious IPs" `
-Direction Inbound -RemoteAddress "203.0.113.0/24" -Action Block
# ลบ Rule
Remove-NetFirewallRule -DisplayName "Allow Web Alt 8080"
# Disable/Enable Rule
Disable-NetFirewallRule -DisplayName "Allow Web Alt 8080"
Enable-NetFirewallRule -DisplayName "Allow Web Alt 8080"
# Export Firewall Rules ออกมาเป็น CSV
Get-NetFirewallRule -Enabled True |
Select-Object DisplayName, Direction, Action, Profile |
Export-Csv -Path "C:\firewall_rules.csv" -NoTypeInformation
จัดการ DNS Server ด้วย PowerShell
ถ้าคุณดูแล Windows DNS Server การจัดการผ่าน PowerShell จะเร็วกว่า DNS Manager GUI มาก:
# ดู DNS Zones ทั้งหมด
Get-DnsServerZone
# สร้าง Forward Lookup Zone
Add-DnsServerPrimaryZone -Name "internal.company.com" -ZoneFile "internal.company.com.dns"
# สร้าง Reverse Lookup Zone
Add-DnsServerPrimaryZone -NetworkID "192.168.1.0/24" -ZoneFile "1.168.192.in-addr.arpa.dns"
# เพิ่ม A Record
Add-DnsServerResourceRecordA -ZoneName "internal.company.com" -Name "web01" -IPv4Address "192.168.1.100"
# เพิ่ม CNAME Record
Add-DnsServerResourceRecordCName -ZoneName "internal.company.com" -Name "portal" -HostNameAlias "web01.internal.company.com"
# เพิ่ม MX Record
Add-DnsServerResourceRecordMX -ZoneName "company.com" -Name "." -MailExchange "mail.company.com" -Preference 10
# ดู Records ใน Zone
Get-DnsServerResourceRecord -ZoneName "internal.company.com"
# ลบ Record
Remove-DnsServerResourceRecord -ZoneName "internal.company.com" -Name "oldserver" -RRType A -Force
# Bulk import DNS records จาก CSV
Import-Csv "dns_records.csv" | ForEach-Object {
Add-DnsServerResourceRecordA -ZoneName $_.Zone -Name $_.Hostname -IPv4Address $_.IP
Write-Host "Added: $($_.Hostname) -> $($_.IP)"
}
จัดการ DHCP Server ด้วย PowerShell
# ดู DHCP Scopes ทั้งหมด
Get-DhcpServerv4Scope
# สร้าง DHCP Scope ใหม่
Add-DhcpServerv4Scope -Name "Office LAN" -StartRange 192.168.1.100 `
-EndRange 192.168.1.200 -SubnetMask 255.255.255.0 -State Active
# ตั้ง DHCP Options (Gateway, DNS)
Set-DhcpServerv4OptionValue -ScopeId 192.168.1.0 -Router 192.168.1.1
Set-DhcpServerv4OptionValue -ScopeId 192.168.1.0 -DnsServer 192.168.1.10,8.8.8.8
Set-DhcpServerv4OptionValue -ScopeId 192.168.1.0 -DnsDomain "internal.company.com"
# สร้าง Reservation (จอง IP ตาม MAC)
Add-DhcpServerv4Reservation -ScopeId 192.168.1.0 -IPAddress 192.168.1.50 `
-ClientId "AA-BB-CC-DD-EE-FF" -Name "Printer01" -Description "HP LaserJet Office"
# ดู Lease ทั้งหมด (ใครได้ IP อะไร)
Get-DhcpServerv4Lease -ScopeId 192.168.1.0 | Format-Table IPAddress, HostName, ClientID, LeaseExpiryTime
# ดูเฉพาะ Active Leases
Get-DhcpServerv4Lease -ScopeId 192.168.1.0 | Where-Object {$_.AddressState -eq "Active"} |
Sort-Object IPAddress | Format-Table -AutoSize
# Export DHCP Lease สำหรับ Documentation
Get-DhcpServerv4Lease -ScopeId 192.168.1.0 |
Select-Object IPAddress, HostName, ClientID, LeaseExpiryTime |
Export-Csv "dhcp_leases.csv" -NoTypeInformation
จัดการ Active Directory Users
AD User management เป็นงานที่ Network/System Admin ทำทุกวัน PowerShell ทำให้จัดการ User เป็นร้อยเป็นพันได้ในไม่กี่นาที:
# ค้นหา User
Get-ADUser -Identity "john.doe" -Properties *
Get-ADUser -Filter 'Name -like "*john*"' | Format-Table Name, SamAccountName, Enabled
# ดู User ทั้งหมดใน OU
Get-ADUser -SearchBase "OU=Sales,DC=company,DC=com" -Filter * |
Format-Table Name, SamAccountName, Enabled
# สร้าง User ใหม่
New-ADUser -Name "Jane Smith" -SamAccountName "jane.smith" `
-UserPrincipalName "[email protected]" `
-GivenName "Jane" -Surname "Smith" `
-Path "OU=IT,DC=company,DC=com" `
-AccountPassword (ConvertTo-SecureString "TempP@ss123!" -AsPlainText -Force) `
-Enabled $true -ChangePasswordAtLogon $true
# Bulk create users จาก CSV
Import-Csv "new_users.csv" | ForEach-Object {
New-ADUser -Name "$($_.FirstName) $($_.LastName)" `
-SamAccountName $_.Username `
-UserPrincipalName "$($_.Username)@company.com" `
-GivenName $_.FirstName -Surname $_.LastName `
-Department $_.Department `
-Path "OU=$($_.Department),DC=company,DC=com" `
-AccountPassword (ConvertTo-SecureString $_.Password -AsPlainText -Force) `
-Enabled $true
Write-Host "Created: $($_.Username)"
}
# Reset Password
Set-ADAccountPassword -Identity "john.doe" `
-Reset -NewPassword (ConvertTo-SecureString "NewP@ss456!" -AsPlainText -Force)
# Disable User (ลาออก)
Disable-ADAccount -Identity "john.doe"
# ดู User ที่ไม่ได้ Login นานเกิน 90 วัน
$cutoff = (Get-Date).AddDays(-90)
Get-ADUser -Filter {LastLogonDate -lt $cutoff -and Enabled -eq $true} -Properties LastLogonDate |
Select-Object Name, SamAccountName, LastLogonDate |
Sort-Object LastLogonDate | Format-Table -AutoSize
# ดู Group Membership
Get-ADPrincipalGroupMembership -Identity "john.doe" | Format-Table Name
จัดการ Hyper-V VMs ด้วย PowerShell
# ดู VM ทั้งหมด
Get-VM | Format-Table Name, State, CPUUsage, MemoryAssigned, Uptime
# สร้าง VM ใหม่
New-VM -Name "WebServer01" -MemoryStartupBytes 4GB `
-NewVHDPath "D:\VMs\WebServer01.vhdx" -NewVHDSizeBytes 100GB `
-SwitchName "External Virtual Switch" -Generation 2
# Start/Stop/Restart VM
Start-VM -Name "WebServer01"
Stop-VM -Name "WebServer01" -Force
Restart-VM -Name "WebServer01"
# Snapshot (Checkpoint)
Checkpoint-VM -Name "WebServer01" -SnapshotName "Before-Update"
Restore-VMCheckpoint -VMName "WebServer01" -Name "Before-Update" -Confirm:$false
# ดู VM Network Adapter
Get-VMNetworkAdapter -VMName "WebServer01" | Format-Table VMName, SwitchName, IPAddresses, MacAddress
# เพิ่ม CPU/Memory
Set-VM -Name "WebServer01" -ProcessorCount 4
Set-VMMemory -VMName "WebServer01" -DynamicMemoryEnabled $true `
-MinimumBytes 2GB -StartupBytes 4GB -MaximumBytes 8GB
# Bulk start VMs ที่ชื่อขึ้นต้นด้วย "Web"
Get-VM -Name "Web*" | Where-Object {$_.State -eq "Off"} | Start-VM
Remote Management — จัดการ Server ระยะไกล
PowerShell Remoting คือความสามารถที่ทำให้ Network Engineer จัดการ Server หลายเครื่องพร้อมกันจากที่เดียว:
Enter-PSSession — Interactive Remote Shell
# เข้า Remote Shell
Enter-PSSession -ComputerName Server01 -Credential (Get-Credential)
# เข้าด้วย SSH (PowerShell 7+)
Enter-PSSession -HostName server01 -UserName admin -SSHTransport
# ออกจาก Remote Shell
Exit-PSSession
Invoke-Command — รัน Command บน Remote Server
# รัน Command บน Server เดียว
Invoke-Command -ComputerName Server01 -ScriptBlock {
Get-Service | Where-Object {$_.Status -eq "Running"} | Measure-Object
}
# รัน Command บน Server หลายเครื่องพร้อมกัน!
$servers = @("Server01", "Server02", "Server03", "Server04", "Server05")
Invoke-Command -ComputerName $servers -ScriptBlock {
[PSCustomObject]@{
Hostname = $env:COMPUTERNAME
OS = (Get-CimInstance Win32_OperatingSystem).Caption
CPU = (Get-CimInstance Win32_Processor).LoadPercentage
MemFree = [math]::Round((Get-CimInstance Win32_OperatingSystem).FreePhysicalMemory / 1MB, 2)
Uptime = (Get-CimInstance Win32_OperatingSystem).LastBootUpTime
}
} | Format-Table -AutoSize
# รัน Script file บน Remote
Invoke-Command -ComputerName $servers -FilePath "C:\Scripts\health_check.ps1"
# Restart Service บนทุก Server
Invoke-Command -ComputerName $servers -ScriptBlock {
Restart-Service -Name "W3SVC" -Force
Write-Host "$env:COMPUTERNAME: IIS Restarted"
}
SSH จาก PowerShell — จัดการ Network Devices
SSH Subsystem ใน PowerShell 7+
# PowerShell 7+ มี SSH transport ในตัว
# ใช้จัดการ Linux server ได้เลย
Enter-PSSession -HostName linux-server -UserName root -SSHTransport
# หรือ Invoke-Command ผ่าน SSH
Invoke-Command -HostName linux-server -UserName root -SSHTransport -ScriptBlock {
uname -a
df -h
free -m
}
Posh-SSH Module — จัดการ Network Device ผ่าน SSH
Posh-SSH เป็น Module ที่สำคัญมากสำหรับ Network Engineer เพราะใช้ SSH เข้า Switch/Router/Firewall แล้วรัน Command ได้:
# ติดตั้ง Posh-SSH
Install-Module -Name Posh-SSH -Force
# SSH เข้า Cisco Switch
$cred = Get-Credential
$session = New-SSHSession -ComputerName "192.168.1.1" -Credential $cred -AcceptKey
# รัน Command
$result = Invoke-SSHCommand -SessionId $session.SessionId -Command "show ip interface brief"
$result.Output
# รัน Command หลายอัน
$commands = @(
"show version",
"show ip route",
"show ip interface brief",
"show mac address-table"
)
foreach ($cmd in $commands) {
$result = Invoke-SSHCommand -SessionId $session.SessionId -Command $cmd
Write-Host "=== $cmd ==="
$result.Output
}
# ปิด Session
Remove-SSHSession -SessionId $session.SessionId
# SSH เข้า MikroTik
$session = New-SSHSession -ComputerName "192.168.88.1" -Credential $cred -AcceptKey
Invoke-SSHCommand -SessionId $session.SessionId -Command "/interface print"
Invoke-SSHCommand -SessionId $session.SessionId -Command "/ip address print"
Invoke-SSHCommand -SessionId $session.SessionId -Command "/ip firewall filter print"
# Bulk config backup จาก Switch หลายตัว
$switches = @("192.168.1.1", "192.168.1.2", "192.168.1.3")
foreach ($sw in $switches) {
$session = New-SSHSession -ComputerName $sw -Credential $cred -AcceptKey
$config = Invoke-SSHCommand -SessionId $session.SessionId -Command "show running-config"
$config.Output | Out-File "C:\Backup\$sw-config-$(Get-Date -Format 'yyyyMMdd').txt"
Remove-SSHSession -SessionId $session.SessionId
Write-Host "Backed up: $sw"
}
Network Documentation อัตโนมัติ
Network Engineer ต้องทำ Documentation เสมอ PowerShell ช่วย Generate documentation อัตโนมัติ:
# สร้าง Network Inventory Report
$servers = Get-ADComputer -Filter {OperatingSystem -like "*Server*"} -Properties OperatingSystem, IPv4Address
$report = $servers | ForEach-Object {
$os = $_.OperatingSystem
$ip = $_.IPv4Address
$name = $_.Name
# Try to get more info remotely
try {
$info = Invoke-Command -ComputerName $name -ScriptBlock {
[PSCustomObject]@{
CPU = (Get-CimInstance Win32_Processor).Name
RAM_GB = [math]::Round((Get-CimInstance Win32_ComputerSystem).TotalPhysicalMemory / 1GB, 1)
Disk_GB = [math]::Round((Get-CimInstance Win32_LogicalDisk -Filter "DeviceID='C:'").Size / 1GB, 1)
}
} -ErrorAction Stop
[PSCustomObject]@{
ServerName = $name
IP = $ip
OS = $os
CPU = $info.CPU
RAM_GB = $info.RAM_GB
Disk_GB = $info.Disk_GB
Status = "Online"
}
} catch {
[PSCustomObject]@{
ServerName = $name; IP = $ip; OS = $os
CPU = "N/A"; RAM_GB = "N/A"; Disk_GB = "N/A"
Status = "Offline/Unreachable"
}
}
}
# Export to HTML report
$report | ConvertTo-Html -Title "Network Inventory $(Get-Date -Format 'yyyy-MM-dd')" `
-PreContent "Server Inventory Report
" |
Out-File "C:\Reports\inventory_$(Get-Date -Format 'yyyyMMdd').html"
# Export to CSV
$report | Export-Csv "C:\Reports\inventory.csv" -NoTypeInformation
Scheduled Tasks สำหรับ Monitoring
# สร้าง Script ที่ตรวจ Server health ทุก 5 นาที
$monitorScript = @'
$servers = @("Server01", "Server02", "Server03")
$logFile = "C:\Logs\monitor_$(Get-Date -Format 'yyyyMMdd').log"
foreach ($server in $servers) {
$ping = Test-Connection -ComputerName $server -Count 1 -Quiet
$timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
if (-not $ping) {
$msg = "$timestamp | ALERT: $server is DOWN!"
Add-Content -Path $logFile -Value $msg
# ส่ง Email แจ้งเตือน
Send-MailMessage -From "[email protected]" -To "[email protected]" `
-Subject "ALERT: $server is DOWN" -Body $msg `
-SmtpServer "smtp.company.com"
} else {
Add-Content -Path $logFile -Value "$timestamp | OK: $server is UP"
}
}
'@
$monitorScript | Out-File "C:\Scripts\monitor.ps1"
# สร้าง Scheduled Task
$action = New-ScheduledTaskAction -Execute "pwsh.exe" -Argument "-File C:\Scripts\monitor.ps1"
$trigger = New-ScheduledTaskTrigger -RepetitionInterval (New-TimeSpan -Minutes 5) -Once -At (Get-Date)
Register-ScheduledTask -TaskName "NetworkMonitor" -Action $action -Trigger $trigger `
-User "SYSTEM" -RunLevel Highest
# Disk space monitor
$diskScript = @'
$threshold = 90 # Alert ถ้า Disk ใช้เกิน 90%
$servers = @("Server01", "Server02", "Server03")
Invoke-Command -ComputerName $servers -ScriptBlock {
Get-CimInstance Win32_LogicalDisk -Filter "DriveType=3" | ForEach-Object {
$usedPercent = [math]::Round(($_.Size - $_.FreeSpace) / $_.Size * 100, 1)
if ($usedPercent -gt $using:threshold) {
[PSCustomObject]@{
Server = $env:COMPUTERNAME
Drive = $_.DeviceID
Used = "$usedPercent%"
Free_GB = [math]::Round($_.FreeSpace / 1GB, 1)
}
}
}
} | ForEach-Object {
Write-Warning "DISK ALERT: $($_.Server) $($_.Drive) = $($_.Used) (Free: $($_.Free_GB) GB)"
}
'@
PowerShell สำหรับ Cisco / MikroTik (SSH-based)
Cisco Switch/Router Management
# Backup config จาก Cisco ทุกตัว
$ciscoDevices = @(
@{Name="Core-SW"; IP="192.168.1.1"},
@{Name="Dist-SW1"; IP="192.168.1.2"},
@{Name="Access-SW1"; IP="192.168.1.11"}
)
$cred = Get-Credential -Message "Cisco Login"
$backupDir = "C:\NetworkBackup\$(Get-Date -Format 'yyyyMMdd')"
New-Item -Path $backupDir -ItemType Directory -Force | Out-Null
foreach ($device in $ciscoDevices) {
try {
$session = New-SSHSession -ComputerName $device.IP -Credential $cred -AcceptKey -ConnectionTimeout 10
$config = Invoke-SSHCommand -SessionId $session.SessionId -Command "show running-config"
$config.Output | Out-File "$backupDir\$($device.Name).cfg"
Remove-SSHSession -SessionId $session.SessionId
Write-Host "[OK] $($device.Name) ($($device.IP))" -ForegroundColor Green
} catch {
Write-Host "[FAIL] $($device.Name) ($($device.IP)): $($_.Exception.Message)" -ForegroundColor Red
}
}
Write-Host "`nBackups saved to: $backupDir"
MikroTik RouterOS Management
# MikroTik health check
$mikrotik = "192.168.88.1"
$session = New-SSHSession -ComputerName $mikrotik -Credential (Get-Credential) -AcceptKey
# System info
$sysInfo = Invoke-SSHCommand -SessionId $session.SessionId -Command "/system resource print"
Write-Host "=== System Resources ==="
$sysInfo.Output
# Interface traffic
$traffic = Invoke-SSHCommand -SessionId $session.SessionId -Command "/interface print stats"
Write-Host "`n=== Interface Stats ==="
$traffic.Output
# DHCP Leases
$leases = Invoke-SSHCommand -SessionId $session.SessionId -Command "/ip dhcp-server lease print"
Write-Host "`n=== DHCP Leases ==="
$leases.Output
# Firewall rules count
$fw = Invoke-SSHCommand -SessionId $session.SessionId -Command "/ip firewall filter print count-only"
Write-Host "`nFirewall rules: $($fw.Output)"
Remove-SSHSession -SessionId $session.SessionId
สร้าง Network Toolkit ด้วย PowerShell
รวม Function ที่ใช้บ่อยเป็น Module:
# NetworkToolkit.psm1
function Get-SubnetScan {
param(
[string]$Subnet = "192.168.1",
[int]$Start = 1,
[int]$End = 254,
[int]$Throttle = 50
)
$Start..$End | ForEach-Object -Parallel {
$ip = "$using:Subnet.$_"
if (Test-Connection -ComputerName $ip -Count 1 -Quiet -TimeoutSeconds 1) {
try {
$dns = (Resolve-DnsName $ip -ErrorAction Stop).NameHost
} catch { $dns = "N/A" }
[PSCustomObject]@{ IP = $ip; Status = "Online"; Hostname = $dns }
}
} -ThrottleLimit $Throttle | Sort-Object { [version]$_.IP }
}
function Get-PortScan {
param(
[string]$Target,
[int[]]$Ports = @(22,53,80,443,3389,5985,8080,8443)
)
$Ports | ForEach-Object {
$result = Test-NetConnection -ComputerName $Target -Port $_ -WarningAction SilentlyContinue
[PSCustomObject]@{
Port = $_
Service = switch($_) { 22{"SSH"} 53{"DNS"} 80{"HTTP"} 443{"HTTPS"} 3389{"RDP"} 5985{"WinRM"} 8080{"HTTP-Alt"} 8443{"HTTPS-Alt"} default{"Unknown"} }
Open = $result.TcpTestSucceeded
}
}
}
function Get-BandwidthTest {
param(
[string]$Target,
[int]$PacketSize = 1472, # MTU 1500 - 28 bytes header
[int]$Count = 100
)
$results = Test-Connection -ComputerName $Target -Count $Count -BufferSize $PacketSize
$latency = $results | Measure-Object -Property Latency -Average -Maximum -Minimum
[PSCustomObject]@{
Target = $Target
Sent = $Count
Received = $results.Count
Loss = "$([math]::Round(($Count - $results.Count) / $Count * 100, 1))%"
AvgLatency = "$([math]::Round($latency.Average, 2)) ms"
MaxLatency = "$([math]::Round($latency.Maximum, 2)) ms"
MinLatency = "$([math]::Round($latency.Minimum, 2)) ms"
}
}
# ใช้งาน:
# Import-Module C:\Scripts\NetworkToolkit.psm1
# Get-SubnetScan -Subnet "10.0.1" -Start 1 -End 50
# Get-PortScan -Target "192.168.1.100"
# Get-BandwidthTest -Target "google.com"
สรุป — PowerShell คือ Swiss Army Knife ของ Network Engineer
PowerShell เปลี่ยนวิธีทำงานของ Network Engineer จากการทำทุกอย่างด้วยมือ เป็นการ Automate ทุกอย่าง ตั้งแต่การ Ping ตรวจสอบ Server, จัดการ Firewall, DNS, DHCP, Active Directory, Hyper-V ไปจนถึงการ SSH เข้า Cisco/MikroTik เพื่อ Backup config อัตโนมัติ
สิ่งสำคัญที่สุดคือ เริ่มจากงานที่ทำซ้ำบ่อย — ถ้าคุณทำอะไรบ่อยเกิน 3 ครั้ง เขียน Script ให้มันทำแทน เริ่มจาก Cmdlet เดียว แล้วค่อยรวมเป็น Script แล้วค่อยรวมเป็น Module ยิ่งเขียนมาก ยิ่งเก่ง และคุณจะมีเวลาไปทำงานที่สำคัญกว่า เช่น วางแผน Network Architecture หรือแก้ปัญหาที่ซับซ้อนจริงๆ
PowerShell 7+ ยังรองรับ Cross-platform (Linux/Mac) และ SSH transport ทำให้เป็นเครื่องมือเดียวที่จัดการได้ทั้ง Windows Server, Linux Server, และ Network Devices ถือเป็น Toolkit ที่คุ้มค่าที่สุดสำหรับ Network Engineer ในปี 2026