[windows] PowerShell을 사용하여 윈도우 로그파일 변환

Posted by 김성철

windows - PowerShell을 사용하여 윈도우 로그파일 변환

사용 이유

윈도우에서 발생하는 이벤트에 대한 로그파일들은 아래의 경로에 생성됨  
C:\Windows\System32\winevt\Logs  
  
해당 로그들은 확장자가 evtx 로 되어있으며 Event Viewer(이벤트 뷰어)라는 도구를 사용해서 봐야함  
  
나는 리눅스와 같은 .log 형식의 파일은 원했음  

변환 방법

아래의 스크립트를 powerShell에서 실행  
※ 관리자 권한으로 실행해야 함  
=====================================================================  
## 로그 파일이 위치한 폴더 경로  
$sourceFolder = "C:\Windows\System32\winevt\Logs"  
## 변환된 로그 파일을 저장할 폴더 경로 (존재하지 않으면 생성됨)  
$destinationFolder = "C:\ConvertedLogs"  
  
## 저장할 폴더가 존재하지 않으면 생성  
if (-not (Test-Path -Path $destinationFolder)) {  
	New-Item -ItemType Directory -Path $destinationFolder  
}  
  
## 폴더 내 모든 .evtx 파일을 찾아서 변환  
Get-ChildItem -Path $sourceFolder -Filter *.evtx | ForEach-Object {  
	$evtxFile = $_.FullName  
	$logFile = Join-Path -Path $destinationFolder -ChildPath ($_.BaseName + ".log")  
  
	## .evtx 파일을 읽고 .log 파일로 변환하여 저장  
	Get-WinEvent -Path $evtxFile | ForEach-Object {  
		$_ | Select-Object -Property TimeCreated, Id, LevelDisplayName, Message  
	} | Format-Table -AutoSize | Out-String | Set-Content -Path $logFile  
  
	Write-Host "Converted $evtxFile to $logFile"  
}  
=====================================================================  

파일 하나 변환하기

=====================================================================  
## .evtx 파일 경로  
$evtxPath = "C:\경로\파일.evtx"  
  
## 내보낼 .log 파일 경로  
$logPath = "C:\경로\파일.log"  
  
## .evtx 파일을 읽고 텍스트 형식으로 변환하여 .log 파일에 저장  
Get-WinEvent -Path $evtxPath | ForEach-Object {  
	$_ | Select-Object -Property TimeCreated, Id, LevelDisplayName, Message  
} | Format-Table -AutoSize | Out-String | Set-Content -Path $logPath  
=====================================================================  
  
- 예시  
=====================================================================  
$evtxPath = "C:\Windows\System32\winevt\Logs\Application.evtx"  
$logPath = "C:\Logs\Application.log"  
  
Get-WinEvent -Path $evtxPath | ForEach-Object {  
	$_ | Select-Object -Property TimeCreated, Id, LevelDisplayName, Message  
} | Format-Table -AutoSize | Out-String | Set-Content -Path $logPath  
=====================================================================  

윈도우 디렉토리에 있는 모든 파일 목록 가져오기

- 목록을 출력  
=====================================================================  
## 파일명을 가져올 폴더 경로  
$folderPath = "C:\경로\폴더"  
  
## 폴더 내 모든 파일의 파일명을 가져와 출력  
Get-ChildItem -Path $folderPath -File | ForEach-Object { $_.Name }  
=====================================================================  
- 목록을 저장  
=====================================================================  
## 파일명을 가져올 폴더 경로  
$folderPath = "C:\경로\폴더"  
  
## 결과를 저장할 텍스트 파일 경로  
$outputFile = "C:\경로\결과.txt"  
  
## 폴더 내 모든 파일의 파일명을 가져와 텍스트 파일에 저장  
Get-ChildItem -Path $folderPath -File | ForEach-Object { $_.Name } | Out-File -FilePath $outputFile  
=====================================================================