
PowerShell คืออะไร? ทำไมถึงเป็นเครื่องมือสำคัญสำหรับ System Administrator
PowerShell คือ Task Automation Framework และ Command-line Shell ที่พัฒนาโดย Microsoft ซึ่งถูกออกแบบมาเพื่อช่วย System Administrator และ IT Professional ในการจัดการระบบ IT ได้อย่างมีประสิทธิภาพ PowerShell ไม่ได้เป็นเพียงแค่ Command Prompt ที่ปรับปรุงแล้ว แต่เป็นภาษาสคริปต์ที่ทรงพลัง สามารถจัดการ Windows Server, Active Directory, Exchange Server, Azure Cloud และอีกมากมายได้จากบรรทัดคำสั่งเพียงไม่กี่บรรทัด
PowerShell ถูกเปิดตัวครั้งแรกในปี 2006 ในชื่อ “Windows PowerShell” และได้รับการพัฒนาอย่างต่อเนื่องจนกระทั่งในปี 2016 Microsoft ได้เปิดตัว “PowerShell Core” ที่เป็น Cross-platform สามารถทำงานได้ทั้งบน Windows, Linux และ macOS ปัจจุบัน PowerShell เวอร์ชัน 7.x เป็นเวอร์ชันล่าสุดที่รวมความสามารถทั้งหมดเข้าด้วยกัน ในปี 2026 PowerShell ได้กลายเป็นเครื่องมือมาตรฐานที่ System Administrator ทุกคนต้องเชี่ยวชาญ โดยเฉพาะในสภาพแวดล้อมที่ใช้ Microsoft Technology Stack
จุดเด่นหลักของ PowerShell ที่ทำให้แตกต่างจาก Shell อื่นๆ คือการทำงานแบบ Object-based ไม่ใช่ Text-based อย่าง Bash หรือ CMD หมายความว่าเมื่อคุณรัน Cmdlet (คำสั่ง) ใน PowerShell ผลลัพธ์ที่ได้คือ .NET Object ที่มี Properties และ Methods ต่างๆ พร้อมให้เข้าถึงได้ทันที ไม่ต้อง Parse Text เหมือน Shell แบบดั้งเดิม ทำให้การประมวลผลข้อมูลมีความแม่นยำและยืดหยุ่นมากกว่า
PowerShell vs CMD vs Bash: เปรียบเทียบความแตกต่าง
เพื่อให้เข้าใจตำแหน่งของ PowerShell ในบรรดา Shell ต่างๆ มาเปรียบเทียบกันในหลายมิติ
Command Prompt (CMD)
CMD หรือ Command Prompt เป็น Shell ดั้งเดิมของ Windows ที่มีมาตั้งแต่ยุค MS-DOS ใช้คำสั่งแบบ Text-based มีความสามารถจำกัด ไม่รองรับ Scripting ที่ซับซ้อน Batch File (.bat) ที่ใช้กับ CMD มีข้อจำกัดมากมาย ไม่มี Error Handling ที่ดี ไม่รองรับ Object และไม่สามารถจัดการระบบที่ซับซ้อนได้ CMD ยังคงมีใช้งานอยู่เพราะความเข้ากันได้กับ Legacy System แต่ Microsoft แนะนำให้เปลี่ยนมาใช้ PowerShell สำหรับงาน Administration ทุกประเภท
Bash (Bourne Again Shell)
Bash เป็น Shell มาตรฐานของ Linux และ macOS มีความสามารถในการ Scripting ที่ดี แต่ทำงานแบบ Text-based ทั้งหมด การ Parse Output ต้องใช้เครื่องมืออย่าง grep, awk, sed ซึ่งอาจเกิดข้อผิดพลาดได้ง่ายหาก Output Format เปลี่ยนไป Bash เหมาะสำหรับ Linux Administration แต่สำหรับ Windows และ Microsoft Services นั้น PowerShell มีความเหมาะสมมากกว่า สำหรับผู้ที่ต้องการศึกษา Linux และ Bash สามารถอ่านบทความเกี่ยวกับ Server & Datacenter ของเราได้
PowerShell
PowerShell เป็น Shell สมัยใหม่ที่ทำงานแบบ Object-based มี Cmdlet มากมายที่ครอบคลุมเกือบทุกด้านของ System Administration มี Pipeline ที่ส่ง Object (ไม่ใช่ Text) มี Error Handling ที่สมบูรณ์ด้วย Try/Catch รองรับ Module System และ Cross-platform
| คุณสมบัติ | CMD | Bash | PowerShell |
|---|---|---|---|
| ประเภท Output | Text | Text | Object |
| Scripting | จำกัดมาก | ดี | ดีมาก |
| Error Handling | พื้นฐาน | Exit Code | Try/Catch/Finally |
| Cross-platform | Windows เท่านั้น | Linux/macOS | ทุก Platform |
| AD Management | ไม่ได้ | ไม่ได้ | เต็มรูปแบบ |
| Module System | ไม่มี | จำกัด | PowerShell Gallery |
| Remote Management | จำกัด | SSH | PSSession + SSH |
การติดตั้ง PowerShell บน Windows, Linux และ macOS
Windows
Windows 10/11 และ Windows Server มี Windows PowerShell 5.1 ติดตั้งมาแล้วในตัว แต่แนะนำให้ติดตั้ง PowerShell 7 เพิ่มเติมเพื่อใช้งานฟีเจอร์ใหม่ วิธีติดตั้ง PowerShell 7 บน Windows สามารถทำได้หลายวิธี ดังนี้
# วิธีที่ 1: ติดตั้งผ่าน winget (แนะนำ)
winget install Microsoft.PowerShell
# วิธีที่ 2: ติดตั้งผ่าน MSI Installer
# ดาวน์โหลดจาก https://github.com/PowerShell/PowerShell/releases
# วิธีที่ 3: ติดตั้งผ่าน Microsoft Store
# ค้นหา "PowerShell" ใน Microsoft Store
# ตรวจสอบเวอร์ชัน
$PSVersionTable.PSVersion
Linux (Ubuntu/Debian)
# อัปเดต Package List และติดตั้ง Prerequisites
sudo apt update
sudo apt install -y wget apt-transport-https software-properties-common
# เพิ่ม Microsoft Repository
wget -q "https://packages.microsoft.com/config/ubuntu/$(lsb_release -rs)/packages-microsoft-prod.deb"
sudo dpkg -i packages-microsoft-prod.deb
# ติดตั้ง PowerShell
sudo apt update
sudo apt install -y powershell
# เรียกใช้งาน
pwsh
macOS
# ติดตั้งผ่าน Homebrew
brew install powershell/tap/powershell
# เรียกใช้งาน
pwsh
Basic Cmdlets: คำสั่งพื้นฐานที่ต้องรู้
Cmdlet (อ่านว่า Command-let) คือคำสั่งใน PowerShell ที่มีรูปแบบ Verb-Noun เช่น Get-Process, Set-Location, New-Item การตั้งชื่อแบบนี้ทำให้จำง่ายและเข้าใจได้ทันทีว่าคำสั่งทำอะไร
คำสั่งช่วยเหลือและค้นหา
# ดูวิธีใช้งาน Cmdlet
Get-Help Get-Process # ดูคำอธิบาย
Get-Help Get-Process -Full # ดูรายละเอียดทั้งหมด
Get-Help Get-Process -Examples # ดูตัวอย่างการใช้งาน
Update-Help # อัปเดตไฟล์ Help
# ค้นหา Cmdlet
Get-Command *process* # ค้นหา Cmdlet ที่เกี่ยวกับ Process
Get-Command -Module ActiveDirectory # ดู Cmdlet ใน Module เฉพาะ
Get-Command -Verb Get # ดู Cmdlet ที่ขึ้นต้นด้วย Get
# ดูสมาชิก (Properties/Methods) ของ Object
Get-Process | Get-Member # ดู Properties และ Methods
Get-Service | Get-Member -MemberType Property # ดูเฉพาะ Properties
คำสั่งจัดการ Process และ Service
# จัดการ Process
Get-Process # ดู Process ทั้งหมด
Get-Process -Name chrome # ดู Process เฉพาะ
Get-Process | Sort-Object CPU -Descending | Select-Object -First 10 # Top 10 CPU
Stop-Process -Name notepad # หยุด Process
Start-Process -FilePath "notepad.exe" # เริ่ม Process
# จัดการ Service
Get-Service # ดู Service ทั้งหมด
Get-Service -Name wuauserv # ดู Service เฉพาะ (Windows Update)
Get-Service | Where-Object {$_.Status -eq 'Running'} # ดู Service ที่ทำงานอยู่
Start-Service -Name Spooler # เริ่ม Service
Stop-Service -Name Spooler # หยุด Service
Restart-Service -Name Spooler # Restart Service
Set-Service -Name Spooler -StartupType Automatic # ตั้ง Startup Type
คำสั่งจัดการไฟล์และโฟลเดอร์
# นำทาง
Set-Location C:\Users # เปลี่ยนไดเรกทอรี (cd)
Get-Location # แสดงไดเรกทอรีปัจจุบัน (pwd)
# จัดการไฟล์
Get-ChildItem # แสดงรายการไฟล์ (ls/dir)
Get-ChildItem -Recurse -Filter *.log # ค้นหาไฟล์ .log
New-Item -Path "C:\Data" -ItemType Directory # สร้างโฟลเดอร์
New-Item -Path "C:\Data\config.txt" -ItemType File # สร้างไฟล์
Copy-Item -Path "source.txt" -Destination "dest.txt" # คัดลอก
Move-Item -Path "old.txt" -Destination "new.txt" # ย้าย/เปลี่ยนชื่อ
Remove-Item -Path "C:\Temp" -Recurse # ลบโฟลเดอร์
# อ่าน/เขียนไฟล์
Get-Content "C:\Data\config.txt" # อ่านไฟล์
Set-Content -Path "output.txt" -Value "Hello" # เขียนไฟล์ (overwrite)
Add-Content -Path "log.txt" -Value "New entry" # เขียนต่อท้าย
Pipeline และ Filtering: พลังที่แท้จริงของ PowerShell
Pipeline (|) คือหัวใจของ PowerShell ที่ทำให้สามารถส่ง Object จาก Cmdlet หนึ่งไปยังอีก Cmdlet หนึ่งได้อย่างต่อเนื่อง ต่างจาก Bash ที่ส่ง Text ผ่าน Pipeline PowerShell ส่ง .NET Object ที่มี Properties และ Methods ครบถ้วน ทำให้สามารถกรอง เรียงลำดับ และจัดรูปแบบข้อมูลได้อย่างยืดหยุ่น
# Where-Object (กรองข้อมูล)
Get-Process | Where-Object {$_.WorkingSet64 -gt 100MB} # Process ที่ใช้ RAM > 100MB
Get-Service | Where-Object {$_.Status -eq 'Stopped' -and $_.StartType -eq 'Automatic'}
# Select-Object (เลือก Properties)
Get-Process | Select-Object Name, CPU, WorkingSet64 | Sort-Object CPU -Descending
# ForEach-Object (ทำซ้ำ)
Get-ChildItem *.log | ForEach-Object {
Write-Host "Processing: $($_.Name) - Size: $($_.Length) bytes"
}
# Measure-Object (นับ/คำนวณ)
Get-Process | Measure-Object WorkingSet64 -Sum -Average # รวมและเฉลี่ย RAM
# Group-Object (จัดกลุ่ม)
Get-Process | Group-Object ProcessName | Sort-Object Count -Descending
# Export/Import ข้อมูล
Get-Process | Export-Csv -Path "processes.csv" -NoTypeInformation
Get-Service | ConvertTo-Json | Out-File "services.json"
Get-Process | Out-GridView # แสดงใน GUI Grid (Windows)
Get-EventLog -LogName System -Newest 100 | Export-Csv "eventlog.csv"
Variables และ Data Types
PowerShell รองรับ Variable และ Data Type หลากหลาย เนื่องจากทำงานบน .NET Framework จึงสามารถใช้ .NET Type ได้ทั้งหมด
# ตัวแปร
$name = "Server01" # String
$count = 42 # Integer
$isRunning = $true # Boolean
$servers = @("Web01", "Web02", "DB01") # Array
$config = @{ # Hashtable
Name = "WebServer"
Port = 443
SSL = $true
}
# String Interpolation
$hostname = "SRV-PROD-01"
Write-Host "Server name is: $hostname"
Write-Host "Server name is: $($hostname.ToUpper())"
# Array Operations
$servers += "DB02" # เพิ่ม Element
$servers[0] # เข้าถึง Element แรก
$servers.Count # นับจำนวน
# Hashtable Operations
$config["Port"] # เข้าถึง Value
$config.SSL # Alternative syntax
$config.Add("Environment", "Production") # เพิ่ม Key-Value
# Type Casting
[int]$port = "8080" # แปลงเป็น Integer
[datetime]$date = "2026-04-08" # แปลงเป็น DateTime
[string]$num = 42 # แปลงเป็น String
Scripting Basics: เขียน Script อัตโนมัติ
การเขียน Script เป็นหัวใจของ Automation ใน PowerShell ทำให้สามารถทำงานซ้ำๆ ได้อย่างรวดเร็วและแม่นยำ ลดโอกาสเกิดข้อผิดพลาดจากการทำงาน Manual
โครงสร้างควบคุม (Control Structures)
# If/ElseIf/Else
$diskSpace = (Get-PSDrive C).Free / 1GB
if ($diskSpace -lt 10) {
Write-Warning "Critical: Disk space low! ($([math]::Round($diskSpace, 2)) GB remaining)"
Send-MailMessage -To "[email protected]" -Subject "Disk Alert" -Body "Low disk space"
} elseif ($diskSpace -lt 50) {
Write-Host "Warning: Disk space is getting low" -ForegroundColor Yellow
} else {
Write-Host "Disk space OK: $([math]::Round($diskSpace, 2)) GB free" -ForegroundColor Green
}
# Switch
$dayOfWeek = (Get-Date).DayOfWeek
switch ($dayOfWeek) {
'Monday' { Write-Host "Starting weekly backup..." }
'Friday' { Write-Host "Running weekend maintenance prep..." }
'Saturday' { Write-Host "Running full backup..." }
default { Write-Host "Regular operations day" }
}
# ForEach Loop
$servers = @("Web01", "Web02", "DB01", "DB02")
foreach ($server in $servers) {
$ping = Test-Connection -ComputerName $server -Count 1 -Quiet
if ($ping) {
Write-Host "$server is online" -ForegroundColor Green
} else {
Write-Host "$server is OFFLINE!" -ForegroundColor Red
}
}
# For Loop
for ($i = 1; $i -le 10; $i++) {
Write-Host "Creating user: TestUser$i"
}
# While Loop
$attempts = 0
while ($attempts -lt 3) {
try {
Test-Connection -ComputerName "server01" -Count 1 -ErrorAction Stop
Write-Host "Connection successful!"
break
} catch {
$attempts++
Write-Host "Attempt $attempts failed. Retrying..."
Start-Sleep -Seconds 5
}
}
# Do-While
do {
$input = Read-Host "Enter 'quit' to exit"
} while ($input -ne 'quit')
Functions
# Function พื้นฐาน
function Get-ServerInfo {
param(
[Parameter(Mandatory=$true)]
[string]$ComputerName,
[switch]$Detailed
)
$os = Get-CimInstance Win32_OperatingSystem -ComputerName $ComputerName
$cpu = Get-CimInstance Win32_Processor -ComputerName $ComputerName
$disk = Get-CimInstance Win32_LogicalDisk -ComputerName $ComputerName -Filter "DriveType=3"
$info = [PSCustomObject]@{
ComputerName = $ComputerName
OS = $os.Caption
RAM_GB = [math]::Round($os.TotalVisibleMemorySize / 1MB, 2)
CPU = $cpu.Name
Uptime = (Get-Date) - $os.LastBootUpTime
}
if ($Detailed) {
$info | Add-Member -NotePropertyName DiskInfo -NotePropertyValue $disk
}
return $info
}
# เรียกใช้งาน
$serverInfo = Get-ServerInfo -ComputerName "Server01" -Detailed
$serverInfo | Format-List
Managing Active Directory with PowerShell
การจัดการ Active Directory (AD) ด้วย PowerShell เป็นหนึ่งในการใช้งานที่ทรงพลังที่สุด สามารถจัดการ User, Group, Computer, OU และ Group Policy ได้ทั้งหมดจาก Command Line สำหรับข้อมูลเพิ่มเติมเกี่ยวกับ Active Directory สามารถอ่านได้จากบทความ Server & Datacenter ของเรา
# ติดตั้ง AD Module
Install-WindowsFeature RSAT-AD-PowerShell
Import-Module ActiveDirectory
# จัดการ User
# สร้าง User ใหม่
New-ADUser -Name "Somchai Jaidee" `
-GivenName "Somchai" `
-Surname "Jaidee" `
-SamAccountName "somchai.j" `
-UserPrincipalName "[email protected]" `
-Path "OU=Users,OU=Bangkok,DC=company,DC=local" `
-AccountPassword (ConvertTo-SecureString "P@ssw0rd123!" -AsPlainText -Force) `
-Enabled $true `
-ChangePasswordAtLogon $true
# ค้นหา User
Get-ADUser -Identity "somchai.j" -Properties *
Get-ADUser -Filter {Department -eq "IT"} -Properties Department, Title |
Select-Object Name, Department, Title
# ดู User ที่ไม่ได้ Login มานาน 90 วัน
$90DaysAgo = (Get-Date).AddDays(-90)
Get-ADUser -Filter {LastLogonDate -lt $90DaysAgo -and Enabled -eq $true} -Properties LastLogonDate |
Select-Object Name, SamAccountName, LastLogonDate |
Sort-Object LastLogonDate
# Disable User ที่ไม่ได้ Login
Get-ADUser -Filter {LastLogonDate -lt $90DaysAgo -and Enabled -eq $true} |
Set-ADUser -Enabled $false
# จัดการ Group
New-ADGroup -Name "IT-Admins" -GroupScope Global -GroupCategory Security `
-Path "OU=Groups,DC=company,DC=local"
Add-ADGroupMember -Identity "IT-Admins" -Members "somchai.j", "admin01"
Get-ADGroupMember -Identity "IT-Admins" | Select-Object Name, SamAccountName
# Bulk User Creation จาก CSV
Import-Csv "C:\Users\new_users.csv" | ForEach-Object {
New-ADUser -Name "$($_.FirstName) $($_.LastName)" `
-GivenName $_.FirstName `
-Surname $_.LastName `
-SamAccountName $_.Username `
-UserPrincipalName "$($_.Username)@company.local" `
-Department $_.Department `
-Title $_.Title `
-Path "OU=Users,DC=company,DC=local" `
-AccountPassword (ConvertTo-SecureString $_.Password -AsPlainText -Force) `
-Enabled $true
Write-Host "Created user: $($_.Username)"
}
# Password Management
Set-ADAccountPassword -Identity "somchai.j" -Reset `
-NewPassword (ConvertTo-SecureString "NewP@ss2026!" -AsPlainText -Force)
Unlock-ADAccount -Identity "somchai.j"
Search-ADAccount -LockedOut | Select-Object Name, SamAccountName
Managing Exchange with PowerShell
PowerShell เป็นเครื่องมือหลักในการจัดการ Microsoft Exchange Server การจัดการ Mailbox, Distribution Group, Transport Rules และ Mail Flow ล้วนทำผ่าน PowerShell ได้อย่างมีประสิทธิภาพ
# เชื่อมต่อ Exchange Server
$Session = New-PSSession -ConfigurationName Microsoft.Exchange `
-ConnectionUri http://exchange-server/PowerShell/ `
-Authentication Kerberos
Import-PSSession $Session
# จัดการ Mailbox
# สร้าง Mailbox
New-Mailbox -Name "Somchai Jaidee" -UserPrincipalName "[email protected]" `
-Password (ConvertTo-SecureString "P@ssw0rd!" -AsPlainText -Force)
# ดูข้อมูล Mailbox
Get-Mailbox -Identity "somchai.j" | Format-List
Get-MailboxStatistics -Identity "somchai.j" | Select-Object DisplayName, TotalItemSize, ItemCount
# ดู Mailbox ขนาดใหญ่
Get-Mailbox -ResultSize Unlimited |
Get-MailboxStatistics |
Sort-Object TotalItemSize -Descending |
Select-Object DisplayName, TotalItemSize, ItemCount -First 20
# ตั้ง Auto Reply (Out of Office)
Set-MailboxAutoReplyConfiguration -Identity "somchai.j" `
-AutoReplyState Enabled `
-InternalMessage "I am out of office." `
-ExternalMessage "I am currently unavailable."
# Distribution Group
New-DistributionGroup -Name "IT-Team" -Members "somchai.j","admin01"
Add-DistributionGroupMember -Identity "IT-Team" -Member "newuser01"
# Mail Flow / Message Tracking
Get-MessageTrackingLog -Sender "[email protected]" -Start (Get-Date).AddDays(-1)
Remote Management: PSSession และ Invoke-Command
การจัดการเซิร์ฟเวอร์จากระยะไกลเป็นความสามารถที่สำคัญของ PowerShell โดยใช้ WinRM (Windows Remote Management) หรือ SSH เป็น Transport Protocol
# เปิดใช้งาน Remote Management
Enable-PSRemoting -Force # เปิดใช้งาน WinRM
Set-Item WSMan:\localhost\Client\TrustedHosts -Value "Server01,Server02"
# Invoke-Command - รันคำสั่งบนเซิร์ฟเวอร์ระยะไกล
Invoke-Command -ComputerName Server01 -ScriptBlock {
Get-Process | Sort-Object CPU -Descending | Select-Object -First 5
}
# รันคำสั่งบนหลายเซิร์ฟเวอร์พร้อมกัน (Parallel)
$servers = @("Web01", "Web02", "DB01", "DB02")
Invoke-Command -ComputerName $servers -ScriptBlock {
[PSCustomObject]@{
ComputerName = $env:COMPUTERNAME
Uptime = (Get-Date) - (Get-CimInstance Win32_OperatingSystem).LastBootUpTime
FreeRAM_GB = [math]::Round((Get-CimInstance Win32_OperatingSystem).FreePhysicalMemory / 1MB, 2)
DiskFree_GB = [math]::Round((Get-PSDrive C).Free / 1GB, 2)
}
} | Format-Table -AutoSize
# PSSession - เปิด Session ค้างไว้
$session = New-PSSession -ComputerName Server01
Enter-PSSession $session # เข้า Interactive Session
Exit-PSSession # ออกจาก Session
# ใช้ Session ที่มีอยู่
Invoke-Command -Session $session -ScriptBlock {
Get-Service | Where-Object {$_.Status -eq 'Stopped'}
}
# คัดลอกไฟล์ผ่าน Session
Copy-Item -Path "C:\Scripts\deploy.ps1" -Destination "C:\Scripts\" -ToSession $session
# ปิด Session
Remove-PSSession $session
Scheduled Tasks: ตั้งเวลาทำงานอัตโนมัติ
PowerShell สามารถสร้างและจัดการ Scheduled Tasks ได้อย่างง่ายดาย ทำให้สามารถ Automate งานประจำต่างๆ ได้
# สร้าง Scheduled Task
$action = New-ScheduledTaskAction -Execute "powershell.exe" `
-Argument "-NoProfile -ExecutionPolicy Bypass -File C:\Scripts\DailyBackup.ps1"
$trigger = New-ScheduledTaskTrigger -Daily -At "02:00AM"
$settings = New-ScheduledTaskSettingsSet -ExecutionTimeLimit (New-TimeSpan -Hours 2) `
-RestartCount 3 -RestartInterval (New-TimeSpan -Minutes 5)
$principal = New-ScheduledTaskPrincipal -UserId "SYSTEM" -LogonType ServiceAccount
Register-ScheduledTask -TaskName "DailyBackup" `
-Action $action -Trigger $trigger `
-Settings $settings -Principal $principal `
-Description "Daily backup script"
# ดู Scheduled Tasks
Get-ScheduledTask | Where-Object {$_.State -eq 'Ready'}
Get-ScheduledTask -TaskName "DailyBackup" | Get-ScheduledTaskInfo
# รัน Task ทันที
Start-ScheduledTask -TaskName "DailyBackup"
# แก้ไข Task
Set-ScheduledTask -TaskName "DailyBackup" -Trigger (New-ScheduledTaskTrigger -Daily -At "03:00AM")
# ลบ Task
Unregister-ScheduledTask -TaskName "DailyBackup" -Confirm:$false
Error Handling: จัดการข้อผิดพลาดอย่างมืออาชีพ
Error Handling ที่ดีเป็นสิ่งสำคัญสำหรับ Script ที่ใช้ใน Production เพราะช่วยให้ Script ทำงานต่อได้แม้พบข้อผิดพลาด และบันทึก Error สำหรับการ Debug ภายหลัง
# Try/Catch/Finally
try {
$service = Get-Service -Name "NonExistentService" -ErrorAction Stop
Restart-Service $service
Write-Host "Service restarted successfully" -ForegroundColor Green
} catch [Microsoft.PowerShell.Commands.ServiceCommandException] {
Write-Warning "Service not found: $($_.Exception.Message)"
} catch {
Write-Error "Unexpected error: $($_.Exception.Message)"
$_ | Out-File "C:\Logs\error.log" -Append
} finally {
Write-Host "Cleanup complete"
}
# ErrorAction Preference
$ErrorActionPreference = "Stop" # หยุดทุก Error
$ErrorActionPreference = "Continue" # แสดง Error แต่ทำงานต่อ (Default)
$ErrorActionPreference = "SilentlyContinue" # ไม่แสดง Error
# Error Variable
Get-Process -Name "fakename" -ErrorAction SilentlyContinue -ErrorVariable myError
if ($myError) {
Write-Host "Error occurred: $myError"
}
# Logging Function
function Write-Log {
param(
[string]$Message,
[ValidateSet("INFO","WARN","ERROR")]
[string]$Level = "INFO"
)
$timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
$logEntry = "$timestamp [$Level] $Message"
Add-Content -Path "C:\Logs\script.log" -Value $logEntry
switch ($Level) {
"INFO" { Write-Host $logEntry -ForegroundColor White }
"WARN" { Write-Host $logEntry -ForegroundColor Yellow }
"ERROR" { Write-Host $logEntry -ForegroundColor Red }
}
}
PowerShell Modules: ขยายความสามารถ
PowerShell Module System ช่วยให้สามารถเพิ่มความสามารถใหม่ๆ ได้อย่างง่ายดาย โดยสามารถติดตั้ง Module จาก PowerShell Gallery ซึ่งเป็น Repository กลางที่มี Module มากกว่า 10,000 ตัว
# ค้นหา Module
Find-Module -Name "*Azure*" # ค้นหา Module
Find-Module -Tag "ActiveDirectory" # ค้นหาด้วย Tag
# ติดตั้ง Module
Install-Module -Name Az -Scope CurrentUser # Azure Module
Install-Module -Name VMware.PowerCLI # VMware Module
Install-Module -Name ImportExcel # Excel Module (ไม่ต้องติดตั้ง Excel)
Install-Module -Name PSWindowsUpdate # Windows Update Module
Install-Module -Name Posh-SSH # SSH Module
# จัดการ Module
Get-Module -ListAvailable # ดู Module ที่ติดตั้ง
Import-Module ActiveDirectory # โหลด Module
Remove-Module ActiveDirectory # ยกเลิกโหลด
# อัปเดต Module
Update-Module -Name Az
# Module ที่มีประโยชน์สำหรับ Sysadmin
# ImportExcel - อ่าน/เขียน Excel ไม่ต้องติดตั้ง Office
Get-Process | Export-Excel -Path "C:\Reports\processes.xlsx" -AutoSize -TableStyle Medium6
# PSWindowsUpdate - จัดการ Windows Update
Get-WindowsUpdate # ดู Update ที่มี
Install-WindowsUpdate -AcceptAll -AutoReboot # ติดตั้ง Update ทั้งหมด
PowerShell DSC (Desired State Configuration)
DSC เป็น Feature ที่ช่วยให้สามารถกำหนดสถานะที่ต้องการ (Desired State) ของเซิร์ฟเวอร์ได้ แล้ว PowerShell จะตรวจสอบและบังคับให้เซิร์ฟเวอร์อยู่ในสถานะที่กำหนดอัตโนมัติ เป็นแนวคิด Infrastructure as Code (IaC) ที่ช่วยให้การจัดการเซิร์ฟเวอร์จำนวนมากเป็นเรื่องง่าย
# ตัวอย่าง DSC Configuration
Configuration WebServerSetup {
param(
[string[]]$ComputerName = "localhost"
)
Node $ComputerName {
# ติดตั้ง IIS
WindowsFeature IIS {
Ensure = "Present"
Name = "Web-Server"
}
# ติดตั้ง ASP.NET
WindowsFeature ASPNet {
Ensure = "Present"
Name = "Web-Asp-Net45"
DependsOn = "[WindowsFeature]IIS"
}
# สร้างโฟลเดอร์สำหรับเว็บไซต์
File WebContent {
Ensure = "Present"
Type = "Directory"
DestinationPath = "C:\inetpub\mysite"
DependsOn = "[WindowsFeature]IIS"
}
# ตั้งค่า Service
Service W3SVC {
Name = "W3SVC"
State = "Running"
StartupType = "Automatic"
DependsOn = "[WindowsFeature]IIS"
}
}
}
# สร้าง MOF File
WebServerSetup -ComputerName "Web01"
# Apply Configuration
Start-DscConfiguration -Path .\WebServerSetup -Wait -Verbose
# ตรวจสอบสถานะ
Test-DscConfiguration -Detailed
Get-DscConfigurationStatus
Security: Execution Policy และ Script Signing
ความปลอดภัยเป็นสิ่งสำคัญเมื่อใช้ PowerShell เพราะ Script ที่มีพลังมากก็อาจเป็นอันตรายได้หากถูกนำไปใช้โดยผู้ไม่หวังดี PowerShell จึงมีระบบ Execution Policy และ Script Signing เพื่อควบคุมความปลอดภัย
Execution Policy
# ดู Execution Policy ปัจจุบัน
Get-ExecutionPolicy
Get-ExecutionPolicy -List # ดูทุกระดับ
# ตั้ง Execution Policy
Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser
# Restricted - ไม่อนุญาตให้รัน Script ใดๆ
# AllSigned - ต้อง Sign ทุก Script
# RemoteSigned - Script จาก Internet ต้อง Sign (แนะนำ)
# Unrestricted - อนุญาตทุก Script (ไม่แนะนำใน Production)
# Bypass - ไม่มีการตรวจสอบใดๆ
Script Signing
# สร้าง Self-Signed Certificate สำหรับ Code Signing
$cert = New-SelfSignedCertificate -Type CodeSigningCert `
-Subject "CN=PowerShell Code Signing" `
-CertStoreLocation Cert:\CurrentUser\My
# Sign Script
Set-AuthenticodeSignature -FilePath "C:\Scripts\MyScript.ps1" -Certificate $cert
# ตรวจสอบ Signature
Get-AuthenticodeSignature -FilePath "C:\Scripts\MyScript.ps1"
Security Best Practices
การใช้ PowerShell อย่างปลอดภัยในองค์กรมีหลักการสำคัญดังนี้ ใช้ Execution Policy แบบ RemoteSigned เป็นอย่างน้อย เปิด Script Block Logging และ Module Logging เพื่อบันทึกการใช้งาน ใช้ Constrained Language Mode สำหรับ User ทั่วไป เปิด PowerShell Transcription เพื่อบันทึก Session ทั้งหมด อัปเดต PowerShell เป็นเวอร์ชันล่าสุดอยู่เสมอ และใช้ Just Enough Administration (JEA) เพื่อจำกัดสิทธิ์
# เปิด Script Block Logging ผ่าน Group Policy หรือ Registry
$regPath = "HKLM:\SOFTWARE\Policies\Microsoft\Windows\PowerShell\ScriptBlockLogging"
New-Item -Path $regPath -Force
Set-ItemProperty -Path $regPath -Name "EnableScriptBlockLogging" -Value 1
# เปิด Transcription
$transcriptPath = "HKLM:\SOFTWARE\Policies\Microsoft\Windows\PowerShell\Transcription"
New-Item -Path $transcriptPath -Force
Set-ItemProperty -Path $transcriptPath -Name "EnableTranscripting" -Value 1
Set-ItemProperty -Path $transcriptPath -Name "OutputDirectory" -Value "C:\PSTranscripts"
Useful Scripts สำหรับ System Administrator
ต่อไปนี้คือ Script ที่มีประโยชน์สำหรับงาน System Administration ประจำวัน สามารถนำไปปรับใช้ได้ทันที
1. Server Health Check Script
# Health-Check.ps1
$servers = Get-Content "C:\Scripts\servers.txt"
$report = @()
foreach ($server in $servers) {
try {
$os = Get-CimInstance Win32_OperatingSystem -ComputerName $server -ErrorAction Stop
$disk = Get-CimInstance Win32_LogicalDisk -ComputerName $server -Filter "DriveType=3"
$report += [PSCustomObject]@{
Server = $server
Status = "Online"
CPU_Pct = (Get-CimInstance Win32_Processor -ComputerName $server).LoadPercentage
RAM_Free = "$([math]::Round($os.FreePhysicalMemory / 1MB, 2)) GB"
Disk_C_Free = "$([math]::Round(($disk | Where-Object DeviceID -eq 'C:').FreeSpace / 1GB, 2)) GB"
Uptime = "$([math]::Round(((Get-Date) - $os.LastBootUpTime).TotalDays, 1)) days"
}
} catch {
$report += [PSCustomObject]@{
Server = $server; Status = "OFFLINE"; CPU_Pct = "N/A"
RAM_Free = "N/A"; Disk_C_Free = "N/A"; Uptime = "N/A"
}
}
}
$report | Format-Table -AutoSize
$report | Export-Csv "C:\Reports\HealthCheck_$(Get-Date -Format 'yyyyMMdd').csv" -NoTypeInformation
2. Disk Space Monitoring Script
# DiskMonitor.ps1
$threshold = 20 # แจ้งเตือนเมื่อเหลือน้อยกว่า 20%
$servers = @("Web01", "Web02", "DB01")
$alerts = foreach ($server in $servers) {
Get-CimInstance Win32_LogicalDisk -ComputerName $server -Filter "DriveType=3" |
Where-Object { ($_.FreeSpace / $_.Size * 100) -lt $threshold } |
Select-Object @{N='Server';E={$server}},
DeviceID,
@{N='Size_GB';E={[math]::Round($_.Size/1GB,2)}},
@{N='Free_GB';E={[math]::Round($_.FreeSpace/1GB,2)}},
@{N='Free_Pct';E={[math]::Round($_.FreeSpace/$_.Size*100,1)}}
}
if ($alerts) {
$body = $alerts | ConvertTo-Html -Title "Disk Space Alert" | Out-String
Send-MailMessage -To "[email protected]" -From "[email protected]" `
-Subject "Disk Space Alert - $(Get-Date -Format 'yyyy-MM-dd')" `
-Body $body -BodyAsHtml -SmtpServer "mail.company.com"
}
3. Log Cleanup Script
# LogCleanup.ps1
$logPaths = @(
"C:\inetpub\logs\LogFiles",
"C:\Windows\Temp",
"C:\Users\*\AppData\Local\Temp"
)
$daysToKeep = 30
$totalFreed = 0
foreach ($path in $logPaths) {
$oldFiles = Get-ChildItem -Path $path -Recurse -File -ErrorAction SilentlyContinue |
Where-Object { $_.LastWriteTime -lt (Get-Date).AddDays(-$daysToKeep) }
$size = ($oldFiles | Measure-Object Length -Sum).Sum / 1MB
$totalFreed += $size
$oldFiles | Remove-Item -Force -ErrorAction SilentlyContinue
Write-Log "Cleaned $path : $([math]::Round($size, 2)) MB freed"
}
Write-Log "Total space freed: $([math]::Round($totalFreed, 2)) MB" -Level INFO
4. AD User Report Script
# AD-UserReport.ps1
$users = Get-ADUser -Filter * -Properties DisplayName, Department, Title,
LastLogonDate, PasswordLastSet, Enabled, WhenCreated |
Select-Object DisplayName, SamAccountName, Department, Title,
LastLogonDate, PasswordLastSet, Enabled, WhenCreated
# Export เป็น Excel (ต้องติดตั้ง ImportExcel Module)
$users | Export-Excel -Path "C:\Reports\AD_Users_$(Get-Date -Format 'yyyyMMdd').xlsx" `
-AutoSize -TableStyle Medium6 -FreezeTopRow `
-Title "Active Directory User Report - $(Get-Date -Format 'dd MMMM yyyy')"
Write-Host "Report generated: $($users.Count) users exported"
สรุป: PowerShell คือทักษะที่ขาดไม่ได้สำหรับ Windows Administrator
PowerShell เป็นเครื่องมือที่ทรงพลังที่สุดสำหรับการจัดการ Windows Server และ Microsoft Services ในปี 2026 ไม่ว่าจะเป็นการจัดการ Active Directory, Exchange Server, Windows Server, Azure Cloud หรือแม้กระทั่ง Linux Server ก็สามารถทำได้ทั้งหมดด้วย PowerShell การเรียนรู้ PowerShell ตั้งแต่พื้นฐานคำสั่ง Cmdlet การใช้ Pipeline การเขียน Script การจัดการ Remote Server ไปจนถึง DSC และ Security จะช่วยเพิ่มประสิทธิภาพการทำงานได้อย่างมหาศาล
สิ่งสำคัญที่สุดคือการฝึกฝนอย่างสม่ำเสมอ เริ่มจากคำสั่งง่ายๆ แล้วค่อยๆ เพิ่มความซับซ้อน ลองเขียน Script สำหรับงานที่ทำเป็นประจำ ทดลองใช้ Remote Management ฝึก Error Handling และศึกษา Module ต่างๆ ที่เกี่ยวข้องกับงานของคุณ ยิ่งใช้ PowerShell มาก ก็จะยิ่งพบว่างาน Administration ที่เคยใช้เวลาหลายชั่วโมง สามารถทำให้เสร็จได้ในไม่กี่นาทีด้วย Script เพียงไม่กี่บรรทัด
สำหรับผู้ที่สนใจศึกษาเพิ่มเติมเกี่ยวกับหัวข้อ IT อื่นๆ สามารถเยี่ยมชมบทความต่างๆ ได้ที่ siamlancard.com ซึ่งมีเนื้อหาครอบคลุมตั้งแต่ Networking, Security, Cloud จนถึง Server Administration และอ่านเพิ่มเติมเกี่ยวกับ IT Knowledge ที่จะช่วยให้คุณเป็น IT Professional ที่ครบเครื่อง