PowerShell ไม่ใช่แค่เครื่องมือ Automation - ยัง ดาวน์โหลดไฟล์จากอินเทอร์เน็ตได้โดยตรง ด้วย Cmdlet Invoke-WebRequest บทความนี้สอนวิธีใช้งานครบถ้วน รองรับทั้งไฟล์สาธารณะและไฟล์ที่ต้อง Login
คำสั่งพื้นฐาน (Basic Syntax)
Invoke-WebRequest -Uri -OutFile
-Uri: URL ของไฟล์ต้นทาง-OutFile: เส้นทางเต็มที่จะบันทึกไฟล์ (รวมชื่อไฟล์)
ตัวอย่าง: ดาวน์โหลดไฟล์ทั่วไป
# ตัวแปร Source และ Destination
$source = 'https://www.majorgeeks.com/files/details/4diskclean_free.html/4dskcln.exe'
$destination = 'C:\programfiles\newfolder\4dskcln.exe'
# ดาวน์โหลด
Invoke-WebRequest -Uri $source -OutFile $destination
หมายเหตุ: โฟลเดอร์ปลายทางต้องมีอยู่จริง (New-Item -ItemType Directory -Force ถ้ายังไม่มี)
กรณีไฟล์ต้อง Login (Authentication Required)
บางไฟล์ต้อง Login ก่อนดาวน์โหลด ใช้ Parameter -Credential
# 1. ขอ Credential (จะมี Popup ให้กรอก User/Pass)
$credential = Get-Credential
# 2. ตั้งค่า Source และ Destination
$source = 'https://example.com/protected/file.zip'
$destination = 'C:\downloads\file.zip'
# 3. ดาวน์โหลดพร้อม Credential
Invoke-WebRequest -Uri $source -OutFile $destination -Credential $credential
พารามิเตอร์เสริมที่มีประโยชน์
| Parameter | คำอธิบาย |
|---|---|
-UseBasicParsing | ใช้ Parser แบบง่าย (เร็วกว่า) - ใน PS 6+ เป็นค่าเริ่มต้นแล้ว |
-Headers @{...} | ส่ง Custom Headers (เช่น User-Agent, Authorization Bearer Token) |
-Proxy | ระบุ Proxy Server |
-TimeoutSec | Timeout วินาที (Default: ไม่มี Timeout) |
-Resume | Resume การดาวน์โหลดที่ขาดหยุด (ต้องรองรับจาก Server) |
ตัวอย่างขั้นสูง: ดาวน์โหลดหลายไฟล์พร้อม Progress Bar
$files = @(
@{Url='https://example.com/file1.zip'; Path='C:\downloads\file1.zip'},
@{Url='https://example.com/file2.zip'; Path='C:\downloads\file2.zip'}
)
foreach ($file in $files) {
Write-Host "Downloading $($file.Url)..." -ForegroundColor Cyan
try {
Invoke-WebRequest -Uri $file.Url -OutFile $file.Path -UseBasicParsing
Write-Host "Done!" -ForegroundColor Green
}
catch {
Write-Error "Failed: $_"
}
}
สรุป
Invoke-WebRequest เป็นเครื่องมือดาวน์โหลดที่ทรงพลังใน PowerShell รองรับ Authentication, Headers, Proxy, Resume ใช้สคริปต์อัตโนมัติได้ ลองนำไปใช้ในงานจริงครับ!