
PowerShell คืออะไร?
PowerShell คือ Command-Line Shell และ Scripting Language ที่พัฒนาโดย Microsoft สำหรับ Automation และ Configuration Management บน Windows (และ Linux/macOS ด้วย PowerShell 7+) เป็นเครื่องมือที่ทุก Windows Admin ต้องรู้ในปี 2026
PowerShell vs CMD
| ลักษณะ | CMD | PowerShell |
|---|---|---|
| Object-Based | ไม่ (Text-Based) | ใช่ (.NET Objects) |
| Scripting | จำกัด (Batch) | เต็มรูปแบบ |
| Remote Management | จำกัด | PowerShell Remoting |
| AD Management | ต้องใช้ Tools แยก | Built-in Module |
| Cross-Platform | Windows เท่านั้น | Windows, Linux, macOS |
คำสั่งพื้นฐาน (Cmdlets)
# PowerShell ใช้ Verb-Noun Naming:
# Get-Command, Set-Item, New-Object, Remove-Item
# =============================================
# Navigation:
Get-Location # pwd
Set-Location C:\Users # cd
Get-ChildItem # ls / dir
Get-ChildItem -Recurse -Filter *.log
# File Operations:
New-Item -ItemType File -Path "test.txt"
New-Item -ItemType Directory -Path "backup"
Copy-Item source.txt destination.txt
Move-Item old.txt new.txt
Remove-Item trash.txt
Get-Content config.txt # cat
Set-Content output.txt "Hello" # echo > file
Add-Content output.txt "World" # echo >> file
# Process:
Get-Process
Get-Process | Where-Object {$_.CPU -gt 50}
Stop-Process -Name notepad
# Service:
Get-Service
Get-Service -Name "wuauserv"
Start-Service -Name "Spooler"
Stop-Service -Name "Spooler"
Restart-Service -Name "Spooler"
# System Info:
Get-ComputerInfo
Get-WmiObject Win32_OperatingSystem
Get-Disk
Get-Volume
Variables และ Data Types
# Variables ($ prefix):
$name = "Server01"
$count = 42
$isActive = $true
$servers = @("web01", "web02", "db01")
$config = @{Name="Server01"; IP="192.168.1.10"; Role="Web"}
# String:
$greeting = "Hello, $name" # Variable expansion
$path = 'C:\Users\$name' # Literal (no expansion)
$multi = @"
Line 1
Line 2: $name
"@
# Array:
$servers = @("web01", "web02", "db01")
$servers[0] # web01
$servers += "app01" # เพิ่ม
$servers.Count # จำนวน
# Hashtable:
$server = @{
Name = "web01"
IP = "192.168.1.10"
Role = "Web Server"
}
$server.Name # web01
$server["IP"] # 192.168.1.10
Pipeline — พลังของ PowerShell
# Pipeline (|) ส่ง Object ไปยังคำสั่งถัดไป:
Get-Process | Sort-Object CPU -Descending | Select-Object -First 10
Get-Service | Where-Object {$_.Status -eq "Running"} | Select-Object Name, Status
Get-ChildItem C:\Logs -Filter *.log | Where-Object {$_.Length -gt 1MB} | Remove-Item
Get-EventLog -LogName System -Newest 100 | Where-Object {$_.EntryType -eq "Error"} | Export-Csv errors.csv
Functions
# Basic Function:
function Get-DiskUsage {
param(
[string]$ComputerName = $env:COMPUTERNAME
)
Get-WmiObject Win32_LogicalDisk -ComputerName $ComputerName |
Where-Object {$_.DriveType -eq 3} |
Select-Object DeviceID,
@{N="Size(GB)";E={[math]::Round($_.Size/1GB,2)}},
@{N="Free(GB)";E={[math]::Round($_.FreeSpace/1GB,2)}},
@{N="Used%";E={[math]::Round(($_.Size-$_.FreeSpace)/$_.Size*100,1)}}
}
Get-DiskUsage -ComputerName "Server01"
Error Handling
# Try-Catch-Finally:
try {
$result = Get-Content "C:\config.txt" -ErrorAction Stop
Write-Host "File loaded successfully"
} catch [System.IO.FileNotFoundException] {
Write-Warning "File not found!"
} catch {
Write-Error "Unexpected error: $_"
} finally {
Write-Host "Cleanup complete"
}
Active Directory Management
# ติดตั้ง AD Module:
Install-WindowsFeature RSAT-AD-PowerShell
# หรือ:
Import-Module ActiveDirectory
# ดู User:
Get-ADUser -Identity john.doe -Properties *
Get-ADUser -Filter {Department -eq "IT"} | Select-Object Name, SamAccountName
# สร้าง User:
New-ADUser -Name "Jane Smith" -SamAccountName "jane.smith" `
-UserPrincipalName "[email protected]" `
-Path "OU=Users,OU=IT,DC=company,DC=local" `
-AccountPassword (ConvertTo-SecureString "TempP@ss123" -AsPlainText -Force) `
-Enabled $true -ChangePasswordAtLogon $true
# ดู Group Members:
Get-ADGroupMember -Identity "Domain Admins" | Select-Object Name
# Disable Inactive Users (90 days):
$90DaysAgo = (Get-Date).AddDays(-90)
Get-ADUser -Filter {LastLogonDate -lt $90DaysAgo -and Enabled -eq $true} |
Disable-ADAccount
Remote Management
# Enable Remoting:
Enable-PSRemoting -Force
# Remote Command:
Invoke-Command -ComputerName Server01 -ScriptBlock { Get-Service }
# Remote Session:
$session = New-PSSession -ComputerName Server01
Enter-PSSession $session
Exit-PSSession
# Multiple Servers:
$servers = @("web01", "web02", "db01")
Invoke-Command -ComputerName $servers -ScriptBlock {
Get-Service | Where-Object {$_.Status -eq "Stopped" -and $_.StartType -eq "Automatic"}
}
Scheduled Tasks
# สร้าง Scheduled Task:
$action = New-ScheduledTaskAction -Execute "PowerShell.exe" `
-Argument "-File C:\Scripts\backup.ps1"
$trigger = New-ScheduledTaskTrigger -Daily -At "02:00"
$settings = New-ScheduledTaskSettingsSet -RunOnlyIfNetworkAvailable
Register-ScheduledTask -TaskName "Daily Backup" `
-Action $action -Trigger $trigger -Settings $settings `
-User "SYSTEM" -RunLevel Highest
# ดู Tasks:
Get-ScheduledTask | Where-Object {$_.State -eq "Ready"}
สรุป: PowerShell สำหรับ Windows Admin
PowerShell เป็นเครื่องมือ Automation ที่ทรงพลังที่สุดสำหรับ Windows Admin ตั้งแต่การจัดการ AD Users, Service, Disk จนถึง Remote Management หลาย Server พร้อมกัน เรียนรู้ Pipeline และ Cmdlets พื้นฐานให้แม่น แล้วคุณจะสามารถ Automate งาน Routine ได้ทั้งหมด