| 일 | 월 | 화 | 수 | 목 | 금 | 토 |
|---|---|---|---|---|---|---|
| 1 | ||||||
| 2 | 3 | 4 | 5 | 6 | 7 | 8 |
| 9 | 10 | 11 | 12 | 13 | 14 | 15 |
| 16 | 17 | 18 | 19 | 20 | 21 | 22 |
| 23 | 24 | 25 | 26 | 27 | 28 | 29 |
| 30 |
- 클라우드플레어 #인터넷 장애 #인터넷 장애 #서버 오류
- #ETRI #광스위치기술 #데이터센터 #AI인프라
- #전자책부업 #PDF전자책 #크몽 #탈잉 #캔바 #컴퓨터부업 #재택부업 #무자본창업 #디지털콘텐츠 #전자책제작 #온라인부업 #월100만원 #패시브인컴 #전자책판매 #전자책마케팅 #2025부업추천
- #무선이어폰 #통화품질 #블루투스이어폰
- AI헬스케어 #OpenAI #ChatGPT #의료AI
- #컴퓨터최적화 #PC최적화프로그램 #무료최적화 #윈도우최적화 #컴퓨터속도향상 #PC성능향상 #게임최적화 #레지스트리정리 #디스크정리 #시스템최적화
- #PC최적화 #컴퓨터속도향상 #윈도우최적화 #SSD트림 #게임성능향상 #메모리최적화 #시작프로그램관리 #디스크정리 #그래픽카드설정 #CPU최적화 #컴퓨터청소 #하드웨어업그레이드 #윈도우11 #윈도우10
- #Windows11 #게임최적화 #FPS향상 #게임모드 #PC성능 #게이밍PC #윈도우11설정 #게임설정 #컴퓨터최적화 #DirectStorage #AutoHDR #그래픽카드설정 #전원모드 #게임성능 #PC게임
- Dall-E
- Stable Diffusion)로 월 100만원 이상 수익 창출하는 7가지 실전 방법. 스톡 이미지 판매부터 NFT
- #PowerShell #스크립트자동화 #윈도우최적화 #시스템관리
- 최신 AI 이미지 생성 도구(Midjourney
- 맞춤 디자인 서비스까지 완벽 정리
- #AI글쓰기 #블로그대필 #ChatGPT #Claude #크몽 #위시켓 #글쓰기부업 #재택부업 ##프리랜서
- #오픈형이어폰 #블루투스이어폰추천 #2025이어폰
- 상품화까지 완벽 가이드
- ChatGPT 크몽
- 게이밍이어폰 #저지연이어폰 #FPS이어폰
- #ChatGPT활용 #디지털콘텐츠 #컴퓨터부업 #온라인수익 #AI영상제작
- #해킹 #사이버공격 #보안관리 #CVE-2025-58034
- #Windows11 #25H2 #생산성향상 #PowerToys #Copilot #SnapLayouts #컴퓨터최적화 #윈도우팁 #업데이트가이드 #
- Stable Diffusion)로 월 200만원 이상 부업 수익을 만드는 실전 가이드. NFT
- #게이밍모니터 #게이밍모니터추천 #144hz #240hz #주사율 #응답속도 #FPS모니터 #게임용모니터 #IPS패널 #VA패널 #QHD모니터 #게이밍기어 #PC주변기기 #게이머 #e스포츠
- 신 AI 이미지 생성 도구(미드저니
- . DeepL
- #AI_PC #NPU #AMD_라이젠_AI #Copilot플러스PC #TOPS #컴퓨터_구매_가이드 #루나레이크#노트북_추천
- #AI이미지생성 #미드저니 #DALL-E #컴퓨터부업 #온라인수익 #스톡이미지 #디지털아트 #프롬프트엔지니어링
- #YannLeCun #Meta #WorldModels #AI혁명
- #AI그래픽디자인 #컴퓨터부업 #캔바 #크몽 #디자인부업 #프리랜서 #월100만원 #재택부업 #Midjourney #AI도구 #2025부업
- 무선 이어폰
- Today
- Total
PC·노트북·이어폰 추천 & 최적화
PowerShell 스크립트 자동화 완벽 가이드 | 실무 생산성 5배 향상 비법 본문
🚀 PowerShell 스크립트 자동화 완벽 가이드
실무에서 바로 쓰는 고급 활용법
🎯 이 글을 읽으면 알 수 있는 것
- PowerShell 스크립트로 반복 작업을 자동화하는 실전 기법
- 시스템 관리 업무 효율을 5배 높이는 핵심 스크립트 예제
- 파일 관리, 네트워크, 시스템 모니터링 자동화 방법
- 보안을 고려한 안전한 스크립트 작성 및 실행 방법
- 실무에서 바로 활용할 수 있는 10가지 자동화 프로젝트
⚡ 왜 지금 PowerShell 자동화를 배워야 할까요?
2025년 현재, IT 업무 환경은 그 어느 때보다 복잡해졌습니다. 수백 대의 서버 관리, 수천 명의 사용자 계정 관리, 매일 반복되는 백업과 모니터링 작업... 이 모든 것을 수동으로 처리하는 것은 불가능에 가깝습니다.
PowerShell은 마이크로소프트가 개발한 강력한 자동화 도구로, 윈도우 시스템 관리자의 필수 기술이 되었습니다. 단순히 명령어를 입력하는 것을 넘어, 복잡한 업무 프로세스를 스크립트로 자동화하여 시간을 절약하고 실수를 줄일 수 있습니다.
실제로 많은 기업에서 PowerShell 자동화를 도입한 후 시스템 관리 업무 시간이 70% 이상 단축되었으며, 인적 오류가 90% 감소했다는 보고가 있습니다. 이제 PowerShell은 선택이 아닌 필수입니다.
🔧 PowerShell 기초 개념 완벽 정리
1. PowerShell이란?
PowerShell은 명령줄 셸(Command-line Shell)과 스크립팅 언어를 결합한 프레임워크입니다. .NET 프레임워크를 기반으로 하며, 객체 지향적인 접근 방식을 사용합니다.
PowerShell vs CMD 비교
| 구분 | PowerShell | CMD (명령 프롬프트) |
|---|---|---|
| 데이터 처리 | 객체 기반 | 텍스트 기반 |
| 확장성 | .NET 프레임워크 활용 가능 | 제한적 |
| 스크립팅 | 강력한 스크립팅 기능 | 배치 파일만 가능 |
| 원격 관리 | PowerShell Remoting 지원 | 제한적 |
| 파이프라인 | 객체 전달 | 텍스트 전달 |
2. 핵심 개념 이해하기
Cmdlet (커맨드렛)
Cmdlet은 PowerShell의 기본 명령 단위입니다. 모든 Cmdlet은 동사-명사 형식을 따르며, 직관적으로 이해할 수 있습니다.
# Cmdlet 예제
Get-Process # 실행 중인 프로세스 조회
Stop-Service # 서비스 중지
New-Item # 새 항목 생성
Remove-Item # 항목 삭제
Set-ExecutionPolicy # 실행 정책 설정변수와 데이터 타입
PowerShell에서 변수는 $ 기호로 시작하며, 동적으로 타입이 결정됩니다.
# 변수 선언과 사용
$userName = "관리자"
$serverCount = 10
$isActive = $true
$servers = @("Server1", "Server2", "Server3")
# 변수 출력
Write-Host "사용자명: $userName"
Write-Host "서버 개수: $serverCount"💼 실무 필수 자동화 시나리오 TOP 10
1. 파일 백업 자동화
매일 반복되는 백업 작업을 자동화하여 시간을 절약하고 실수를 방지할 수 있습니다.
# 자동 백업 스크립트
$sourcePath = "C:\Important\Documents"
$backupPath = "D:\Backup\$(Get-Date -Format 'yyyy-MM-dd')"
$logFile = "C:\Logs\backup_log.txt"
# 백업 디렉토리 생성
if (-not (Test-Path $backupPath)) {
New-Item -ItemType Directory -Path $backupPath -Force
}
# 파일 복사
try {
Copy-Item -Path $sourcePath -Destination $backupPath -Recurse -Force
$message = "$(Get-Date) - 백업 성공: $sourcePath -> $backupPath"
Add-Content -Path $logFile -Value $message
Write-Host $message -ForegroundColor Green
}
catch {
$errorMessage = "$(Get-Date) - 백업 실패: $_"
Add-Content -Path $logFile -Value $errorMessage
Write-Host $errorMessage -ForegroundColor Red
}2. 디스크 공간 모니터링
서버의 디스크 공간이 부족해지기 전에 자동으로 알림을 받을 수 있습니다.
# 디스크 공간 모니터링 스크립트
$threshold = 20 # 경고 임계값 (%)
$computerName = $env:COMPUTERNAME
$disks = Get-WmiObject Win32_LogicalDisk -Filter "DriveType=3"
foreach ($disk in $disks) {
$freeSpace = [math]::Round(($disk.FreeSpace / $disk.Size) * 100, 2)
if ($freeSpace -lt $threshold) {
$message = @"
경고: 디스크 공간 부족!
컴퓨터: $computerName
드라이브: $($disk.DeviceID)
여유 공간: $freeSpace%
전체 크기: $([math]::Round($disk.Size / 1GB, 2)) GB
사용 가능: $([math]::Round($disk.FreeSpace / 1GB, 2)) GB
"@
Write-Host $message -ForegroundColor Red
# 이메일 알림 보내기 (선택사항)
# Send-MailMessage -To "admin@company.com" -Subject "디스크 공간 경고" -Body $message
}
}3. 로그 파일 정리 자동화
오래된 로그 파일을 자동으로 삭제하여 디스크 공간을 확보합니다.
# 30일 이상된 로그 파일 삭제
$logPath = "C:\Logs"
$daysToKeep = 30
$dateLimit = (Get-Date).AddDays(-$daysToKeep)
$oldFiles = Get-ChildItem -Path $logPath -Recurse -File |
Where-Object { $_.LastWriteTime -lt $dateLimit }
$totalSize = ($oldFiles | Measure-Object -Property Length -Sum).Sum
$fileCount = $oldFiles.Count
Write-Host "삭제 대상 파일: $fileCount 개"
Write-Host "확보 예상 공간: $([math]::Round($totalSize / 1MB, 2)) MB"
$confirmation = Read-Host "정말 삭제하시겠습니까? (Y/N)"
if ($confirmation -eq 'Y') {
$oldFiles | Remove-Item -Force
Write-Host "로그 파일 정리 완료!" -ForegroundColor Green
} else {
Write-Host "작업이 취소되었습니다."
}4. 사용자 계정 일괄 생성
CSV 파일을 읽어 Active Directory 사용자를 대량으로 생성합니다.
# CSV 파일에서 사용자 정보 읽어 계정 생성
# CSV 형식: Name,Department,Title,Manager
$csvPath = "C:\Users\NewUsers.csv"
$users = Import-Csv -Path $csvPath
foreach ($user in $users) {
$params = @{
Name = $user.Name
GivenName = $user.Name.Split()[0]
Surname = $user.Name.Split()[1]
SamAccountName = $user.Name.Replace(' ', '.').ToLower()
Department = $user.Department
Title = $user.Title
Manager = $user.Manager
Enabled = $true
ChangePasswordAtLogon = $true
}
try {
New-ADUser @params
Write-Host "사용자 생성 완료: $($user.Name)" -ForegroundColor Green
}
catch {
Write-Host "사용자 생성 실패: $($user.Name) - $_" -ForegroundColor Red
}
}5. 시스템 정보 보고서 생성
서버의 상세 정보를 HTML 보고서로 자동 생성합니다.
# 시스템 정보 수집 및 HTML 보고서 생성
$computerName = $env:COMPUTERNAME
$reportPath = "C:\Reports\SystemReport_$(Get-Date -Format 'yyyyMMdd').html"
# 시스템 정보 수집
$os = Get-WmiObject Win32_OperatingSystem
$cpu = Get-WmiObject Win32_Processor
$memory = Get-WmiObject Win32_PhysicalMemory
$disk = Get-WmiObject Win32_LogicalDisk -Filter "DriveType=3"
# HTML 보고서 생성
$html = @"
시스템 정보 보고서
생성 일시: $(Get-Date -Format 'yyyy-MM-dd HH:mm:ss')
컴퓨터명: $computerName
운영체제 정보
| 항목 | 값 |
|---|---|
| OS 이름 | $($os.Caption) |
| 버전 | $($os.Version) |
| 설치 날짜 | $($os.ConvertToDateTime($os.InstallDate)) |
CPU 정보
| 항목 | 값 |
|---|---|
| 프로세서 | $($cpu.Name) |
| 코어 수 | $($cpu.NumberOfCores) |
| 논리 프로세서 | $($cpu.NumberOfLogicalProcessors) |
메모리 정보
| 전체 메모리 | 사용 가능 메모리 |
|---|---|
| $([math]::Round($os.TotalVisibleMemorySize / 1MB, 2)) GB | $([math]::Round($os.FreePhysicalMemory / 1MB, 2)) GB |
"@ $html | Out-File -FilePath $reportPath -Encoding UTF8 Write-Host "보고서 생성 완료: $reportPath" -ForegroundColor Green Invoke-Item $reportPath # 보고서 자동 열기6. 서비스 상태 모니터링
중요한 서비스가 중지되면 자동으로 재시작하고 로그를 남깁니다.
# 중요 서비스 모니터링 및 자동 재시작
$criticalServices = @("wuauserv", "MSSQLSERVER", "W3SVC")
$logFile = "C:\Logs\ServiceMonitor.log"
foreach ($serviceName in $criticalServices) {
$service = Get-Service -Name $serviceName -ErrorAction SilentlyContinue
if ($service -eq $null) {
$message = "$(Get-Date) - 경고: 서비스 '$serviceName' 를 찾을 수 없습니다."
Add-Content -Path $logFile -Value $message
continue
}
if ($service.Status -ne 'Running') {
$message = "$(Get-Date) - 서비스 '$serviceName' 이(가) 중지됨. 재시작 시도 중..."
Add-Content -Path $logFile -Value $message
Write-Host $message -ForegroundColor Yellow
try {
Start-Service -Name $serviceName
$message = "$(Get-Date) - 서비스 '$serviceName' 재시작 성공"
Add-Content -Path $logFile -Value $message
Write-Host $message -ForegroundColor Green
}
catch {
$message = "$(Get-Date) - 서비스 '$serviceName' 재시작 실패: $_"
Add-Content -Path $logFile -Value $message
Write-Host $message -ForegroundColor Red
}
}
}7. 네트워크 연결 테스트 자동화
여러 서버의 네트워크 연결 상태를 일괄 확인합니다.
# 서버 목록 네트워크 연결 테스트
$servers = @(
"192.168.1.10",
"192.168.1.20",
"webserver.company.com",
"dbserver.company.com"
)
$results = @()
foreach ($server in $servers) {
Write-Host "테스트 중: $server" -NoNewline
$ping = Test-Connection -ComputerName $server -Count 2 -Quiet
$result = [PSCustomObject]@{
Server = $server
Status = if ($ping) { "온라인" } else { "오프라인" }
Timestamp = Get-Date -Format 'yyyy-MM-dd HH:mm:ss'
}
$results += $result
if ($ping) {
Write-Host " ✓ 연결됨" -ForegroundColor Green
} else {
Write-Host " ✗ 연결 실패" -ForegroundColor Red
}
}
# 결과를 CSV 파일로 저장
$results | Export-Csv -Path "C:\Reports\NetworkTest_$(Get-Date -Format 'yyyyMMdd_HHmmss').csv" -NoTypeInformation
Write-Host "`n테스트 완료! 결과가 저장되었습니다."8. 대용량 파일 검색 및 정리
특정 크기 이상의 파일을 찾아서 관리합니다.
# 100MB 이상 파일 검색
$searchPath = "C:\"
$sizeThreshold = 100MB
Write-Host "대용량 파일 검색 중... (100MB 이상)" -ForegroundColor Yellow
$largeFiles = Get-ChildItem -Path $searchPath -Recurse -File -ErrorAction SilentlyContinue |
Where-Object { $_.Length -gt $sizeThreshold } |
Sort-Object Length -Descending |
Select-Object -First 50
# 결과 출력
$largeFiles | Format-Table Name,
@{Label="크기(MB)"; Expression={[math]::Round($_.Length / 1MB, 2)}},
@{Label="경로"; Expression={$_.DirectoryName}},
LastWriteTime -AutoSize
# CSV로 저장
$largeFiles | Select-Object Name,
@{Name="크기_MB"; Expression={[math]::Round($_.Length / 1MB, 2)}},
@{Name="전체경로"; Expression={$_.FullName}},
LastWriteTime |
Export-Csv -Path "C:\Reports\LargeFiles_$(Get-Date -Format 'yyyyMMdd').csv" -NoTypeInformation
Write-Host "`n총 $($largeFiles.Count)개의 대용량 파일을 찾았습니다." -ForegroundColor Green9. Windows 업데이트 자동화
Windows 업데이트를 스크립트로 자동 설치합니다.
# Windows Update 모듈 설치 (최초 1회)
# Install-Module PSWindowsUpdate -Force
# Windows 업데이트 확인 및 설치
Import-Module PSWindowsUpdate
Write-Host "사용 가능한 업데이트 확인 중..." -ForegroundColor Yellow
# 업데이트 목록 조회
$updates = Get-WindowsUpdate
if ($updates.Count -eq 0) {
Write-Host "설치할 업데이트가 없습니다." -ForegroundColor Green
} else {
Write-Host "발견된 업데이트: $($updates.Count)개" -ForegroundColor Yellow
# 업데이트 설치
Install-WindowsUpdate -AcceptAll -AutoReboot | Out-File "C:\Logs\WindowsUpdate_$(Get-Date -Format 'yyyyMMdd').log"
Write-Host "업데이트 설치가 완료되었습니다." -ForegroundColor Green
}10. 폴더 권한 감사 자동화
폴더의 권한 설정을 확인하고 보고서를 생성합니다.
# 폴더 권한 감사
$folderPath = "C:\Shares"
$reportPath = "C:\Reports\PermissionAudit_$(Get-Date -Format 'yyyyMMdd').csv"
$results = @()
Get-ChildItem -Path $folderPath -Directory | ForEach-Object {
$folder = $_
$acl = Get-Acl -Path $folder.FullName
foreach ($access in $acl.Access) {
$result = [PSCustomObject]@{
폴더명 = $folder.Name
전체경로 = $folder.FullName
사용자 = $access.IdentityReference
권한 = $access.FileSystemRights
접근제어타입 = $access.AccessControlType
상속여부 = $access.IsInherited
}
$results += $result
}
}
$results | Export-Csv -Path $reportPath -NoTypeInformation -Encoding UTF8
Write-Host "권한 감사 완료! 보고서: $reportPath" -ForegroundColor Green🔒 보안 및 모범 사례
1. 실행 정책 (Execution Policy) 이해하기
PowerShell 스크립트의 실행을 제어하는 보안 기능입니다.
| 정책 | 설명 | 사용 시나리오 |
|---|---|---|
| Restricted | 스크립트 실행 불가 (기본값) | 최고 수준의 보안 필요 시 |
| AllSigned | 서명된 스크립트만 실행 | 기업 환경, 프로덕션 서버 |
| RemoteSigned | 로컬 스크립트와 서명된 원격 스크립트 실행 | 일반적인 개발/운영 환경 |
| Unrestricted | 모든 스크립트 실행 (경고 표시) | 테스트 환경 |
| Bypass | 모든 제한 없음 | 자동화 작업 (주의 필요) |
# 현재 실행 정책 확인
Get-ExecutionPolicy
# 실행 정책 변경 (관리자 권한 필요)
Set-ExecutionPolicy RemoteSigned -Scope CurrentUser
# 일시적으로 정책 우회하여 스크립트 실행
PowerShell.exe -ExecutionPolicy Bypass -File .\script.ps1- 프로덕션 환경에서는 AllSigned 또는 RemoteSigned 정책 사용 권장
- Unrestricted나 Bypass는 테스트 환경에서만 사용
- 의심스러운 출처의 스크립트는 실행하지 말 것
2. 자격 증명 안전하게 관리하기
스크립트에 비밀번호를 하드코딩하지 마세요!
# ❌ 나쁜 예 - 비밀번호 하드코딩
$password = ConvertTo-SecureString "MyPassword123" -AsPlainText -Force
$credential = New-Object System.Management.Automation.PSCredential ("admin", $password)
# ✅ 좋은 예 1 - 대화형 자격 증명 입력
$credential = Get-Credential -Message "관리자 자격 증명을 입력하세요"
# ✅ 좋은 예 2 - 암호화된 자격 증명 저장/불러오기
# 자격 증명 저장
$credential = Get-Credential
$credential | Export-Clixml -Path "C:\Secure\Credential.xml"
# 자격 증명 불러오기
$credential = Import-Clixml -Path "C:\Secure\Credential.xml"
# ✅ 좋은 예 3 - Windows Credential Manager 활용
Install-Module CredentialManager -Force
New-StoredCredential -Target "MyApp" -UserName "admin" -Password "SecurePass123"
$credential = Get-StoredCredential -Target "MyApp"3. 에러 처리 모범 사례
# Try-Catch-Finally를 활용한 체계적 에러 처리
$logPath = "C:\Logs\ErrorLog.txt"
try {
# 위험한 작업 수행
$result = Get-Content "C:\ImportantFile.txt" -ErrorAction Stop
# 파일 처리
$processedData = $result | ForEach-Object { $_.ToUpper() }
# 결과 저장
$processedData | Out-File "C:\ProcessedFile.txt"
Write-Host "처리 완료!" -ForegroundColor Green
}
catch [System.IO.FileNotFoundException] {
$errorMsg = "파일을 찾을 수 없습니다: $_"
Write-Host $errorMsg -ForegroundColor Red
Add-Content -Path $logPath -Value "$(Get-Date) - $errorMsg"
}
catch [System.UnauthorizedAccessException] {
$errorMsg = "접근 권한이 없습니다: $_"
Write-Host $errorMsg -ForegroundColor Red
Add-Content -Path $logPath -Value "$(Get-Date) - $errorMsg"
}
catch {
$errorMsg = "예상치 못한 오류 발생: $_"
Write-Host $errorMsg -ForegroundColor Red
Add-Content -Path $logPath -Value "$(Get-Date) - $errorMsg"
}
finally {
# 정리 작업 (항상 실행됨)
Write-Host "작업 종료 - $(Get-Date)"
}4. 스크립트 성능 최적화
# ❌ 비효율적인 방법
$files = Get-ChildItem C:\LargeFolder -Recurse
foreach ($file in $files) {
if ($file.Extension -eq ".log") {
# 처리
}
}
# ✅ 효율적인 방법
$files = Get-ChildItem C:\LargeFolder -Recurse -Filter "*.log"
$files | ForEach-Object -Parallel {
# 병렬 처리 (PowerShell 7+)
# 각 파일 처리
} -ThrottleLimit 10
# 성능 측정
Measure-Command {
# 측정할 코드
Get-Process
}📊 실전 프로젝트: 종합 서버 모니터링 시스템
지금까지 배운 내용을 종합하여 완전한 서버 모니터링 시스템을 구축해봅시다.
# 종합 서버 모니터링 스크립트
param(
[string]$ServerListFile = "C:\Config\servers.txt",
[int]$DiskThreshold = 20,
[int]$CpuThreshold = 80,
[int]$MemoryThreshold = 85
)
# 로그 함수
function Write-Log {
param([string]$Message, [string]$Level = "INFO")
$logPath = "C:\Logs\ServerMonitor.log"
$timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
$logMessage = "[$timestamp] [$Level] $Message"
Add-Content -Path $logPath -Value $logMessage
switch ($Level) {
"ERROR" { Write-Host $logMessage -ForegroundColor Red }
"WARNING" { Write-Host $logMessage -ForegroundColor Yellow }
"SUCCESS" { Write-Host $logMessage -ForegroundColor Green }
default { Write-Host $logMessage }
}
}
# 서버 목록 로드
if (-not (Test-Path $ServerListFile)) {
Write-Log "서버 목록 파일을 찾을 수 없습니다: $ServerListFile" "ERROR"
exit 1
}
$servers = Get-Content $ServerListFile
# 모니터링 결과 저장
$results = @()
foreach ($server in $servers) {
Write-Log "서버 모니터링 시작: $server" "INFO"
try {
# 네트워크 연결 확인
if (-not (Test-Connection -ComputerName $server -Count 1 -Quiet)) {
Write-Log "서버 연결 실패: $server" "ERROR"
continue
}
# 디스크 공간 확인
$disks = Get-WmiObject Win32_LogicalDisk -ComputerName $server -Filter "DriveType=3"
foreach ($disk in $disks) {
$freePercent = [math]::Round(($disk.FreeSpace / $disk.Size) * 100, 2)
if ($freePercent -lt $DiskThreshold) {
Write-Log "디스크 공간 부족 - $server $($disk.DeviceID): $freePercent%" "WARNING"
}
}
# CPU 사용률 확인
$cpu = Get-WmiObject Win32_Processor -ComputerName $server
$cpuUsage = $cpu.LoadPercentage
if ($cpuUsage -gt $CpuThreshold) {
Write-Log "CPU 사용률 높음 - $server : $cpuUsage%" "WARNING"
}
# 메모리 사용률 확인
$os = Get-WmiObject Win32_OperatingSystem -ComputerName $server
$memoryUsage = [math]::Round((($os.TotalVisibleMemorySize - $os.FreePhysicalMemory) / $os.TotalVisibleMemorySize) * 100, 2)
if ($memoryUsage -gt $MemoryThreshold) {
Write-Log "메모리 사용률 높음 - $server : $memoryUsage%" "WARNING"
}
# 결과 저장
$result = [PSCustomObject]@{
ServerName = $server
Status = "정상"
CpuUsage = $cpuUsage
MemoryUsage = $memoryUsage
DiskFree = "$freePercent%"
CheckTime = Get-Date -Format 'yyyy-MM-dd HH:mm:ss'
}
$results += $result
Write-Log "서버 모니터링 완료: $server" "SUCCESS"
}
catch {
Write-Log "모니터링 중 오류 발생 - $server : $_" "ERROR"
}
}
# 보고서 생성
$reportPath = "C:\Reports\ServerMonitor_$(Get-Date -Format 'yyyyMMdd_HHmmss').csv"
$results | Export-Csv -Path $reportPath -NoTypeInformation -Encoding UTF8
Write-Log "모니터링 완료! 보고서: $reportPath" "SUCCESS"
# HTML 이메일 보고서 생성 (선택사항)
$htmlReport = $results | ConvertTo-Html -Head @"
"@ | Out-String # 이메일 발송 (SMTP 설정 필요) # Send-MailMessage -To "admin@company.com" -Subject "서버 모니터링 보고서" -Body $htmlReport -BodyAsHtml⚙️ 작업 스케줄러 등록하기
스크립트를 자동으로 실행하려면 Windows 작업 스케줄러에 등록해야 합니다.
- 작업 스케줄러 열기
Windows 키 + R → taskschd.msc 입력 → Enter - 새 작업 만들기
'작업 만들기' 클릭 (기본 작업 만들기는 제한적) - 일반 탭 설정
- 이름: "서버 모니터링 자동화"
- 가장 높은 수준의 권한으로 실행 체크
- 사용자의 로그온 여부에 관계없이 실행 선택 - 트리거 탭 설정
- '새로 만들기' 클릭
- 매일 또는 매시간 등 실행 주기 설정 - 동작 탭 설정
- 프로그램/스크립트:PowerShell.exe
- 인수 추가:-ExecutionPolicy Bypass -File "C:\Scripts\Monitor.ps1"
# PowerShell로 작업 스케줄러 등록
$action = New-ScheduledTaskAction -Execute 'PowerShell.exe' `
-Argument '-ExecutionPolicy Bypass -File "C:\Scripts\Monitor.ps1"'
$trigger = New-ScheduledTaskTrigger -Daily -At 9am
$settings = New-ScheduledTaskSettingsSet -StartWhenAvailable -DontStopOnIdleEnd
Register-ScheduledTask -TaskName "서버 모니터링" `
-Action $action `
-Trigger $trigger `
-Settings $settings `
-Description "매일 오전 9시 서버 상태 모니터링" `
-User "SYSTEM" `
-RunLevel Highest🎓 학습 리소스 및 다음 단계
추천 학습 경로
- PowerShell 공식 문서
Microsoft Learn의 PowerShell 모듈을 통해 체계적으로 학습 - GitHub 스크립트 저장소
실전 스크립트 예제를 분석하고 커스터마이징 - PowerShell Gallery
커뮤니티에서 공유한 모듈 활용 - 고급 주제
- PowerShell DSC (Desired State Configuration)
- PowerShell Remoting
- REST API 연동
- Azure 자동화
실전 연습 프로젝트 아이디어
- 웹사이트 가용성 모니터링 시스템
- Active Directory 사용자 관리 자동화
- IIS 로그 분석 및 보고서 생성
- SQL Server 백업 자동화
- Office 365 사용자 프로비저닝
- VM 자동 생성/삭제 스크립트
- 보안 취약점 스캐너
- 소프트웨어 라이선스 추적 시스템
🎉 축하합니다!
이제 PowerShell 자동화의 기초부터 고급 기법까지 모두 익혔습니다. 실무에서 반복되는 작업이 있다면 스크립트로 자동화해보세요. 처음에는 간단한 작업부터 시작하여 점진적으로 복잡한 자동화 시스템을 구축해나가시길 바랍니다.
Remember: 좋은 스크립트는 한 번에 완성되지 않습니다. 지속적인 개선과 최적화를 통해 완성도를 높여가세요!
💬 마무리
PowerShell 자동화는 IT 전문가의 필수 역량입니다. 단순 반복 작업에 소비되는 시간을 줄이고, 더 가치 있는 업무에 집중할 수 있게 해줍니다. 이 가이드에서 소개한 스크립트들은 실무 환경에서 바로 활용할 수 있도록 설계되었습니다.
여러분의 업무 환경에 맞게 커스터마이징하여 사용하시고, 자동화를 통해 생산성을 크게 향상시키시길 바랍니다. 궁금한 점이나 추가로 알고 싶은 내용이 있다면 댓글로 남겨주세요!
📌 관련 태그
'튜토리얼 &가이드 > 심화 강좌' 카테고리의 다른 글
| 윈도우 작업 스케줄러 활용한 PC 자동화 심화 가이드 (0) | 2025.11.22 |
|---|---|
| Windows 레지스트리 최적화 완벽 가이드 | PC 성능 극대화 (1) | 2025.11.21 |
| 윈도우 보안 심화 가이드 - 랜섬웨어 차단, 제로 트러스트 구축, BitLocker 암호화, 고급 방화벽 설정까지 실전 보안 전략 완벽 정리 (0) | 2025.11.08 |
| 최신 랜섬웨어 대응 전략 완벽 가이드. 기업 사이버 보안 실전 대응법, 이중 갈취 방어, 제로 트러스트 아키텍처 구축까지 전문가 수준의 심화 가이드 (0) | 2025.11.08 |
| 윈도우 11 고급 최적화 및 시스템 튜닝 심화 과정 2025 | 전문가 가이드 (0) | 2025.11.07 |
