본문 바로가기

Software

Powershell 명령어를 활용한 시스템 분석 - 여러가지 명령어들

1 Powershell 명령어

본 포스팅에 사용한 파워쉘 버전은 5.1버전이다.

1.1 Get-…

1.1.1 Get-Process

프로세스 정보를 확인한다

(gps) get-process

[s] 로 시작하는 모든 프로세스를 확인한다

get-process [s]*

어떤 프로세스가 700개 이상의 핸들을 점유하고 있는 지 확인한다

get-process | where handles -gt 700 | sort cpu -descending

workingset 메모리가 100M 이상인 프로세스를 확인한다

get-process | where-object {$_.workingset -gt 100mb} | sort pm -descending

프로세스 중 마지막 10개만 정렬해서 htm 문서화한다

get-process | select-object -last 10 | select-object name, handle, cpu, id, workingset | convertto-html | out-file c:\process.htm

프로세스 이름이 sv로 시작하는 프로세스를 확인한다

get-process | where ProcessName -Like sv*

gvim 프로세스의 자세한 정보를 확인한다

get-process gvim | format-list *

wmi*로 시작하는 프로세스를 전부 종료한다

get-process | where processname -like wmi* | kill

vmw*로 시작하는 프로세스를 전부 종료한다

get-process | where processname -like vmw* | stop-process -Force

각각 프로세스들이 언제 시작됐는지 확인한다

get-process | select name, starttime

1.1.2 Get-Scheduledtask

ashley라는 이름의 예약작업 정보를 확인한다

get-scheduledtask | where taskname -like *ashley* | fl *

1.1.3 Get-WmiObject

win32_pingstatus를 이용해 IP를 확인한다

get-wmiobject win32_pingstatus -filter "address='localhost'"

win32_logicaldisk를 이용해 c:\ 정보를 확인한다

get-wmiobject win32_logicaldisk

설치된 프로그램 중 sql이 포함된 프로그램을 확인한다

get-wmiobject win32_product | where-object -filterscript { $_.tostring() -match "sql"}

1.1.4 Get-Childitem

dir 과 비슷한 명령어

(dir)get-childitem

현재 폴더에서 *.html 파일 중 100mb 이하인 파일을 모두 삭제

get-childitem .\* -include *.html | where-object -filterscript { $_.length -lt 100mb} | remove-item -force

해당 폴더에서 .jpg 파일을 전부 찾은 다음 이름순에 따라 겹치는 항목 없이 정렬

get-childitem c:\users\gyurs\desktop\edward\ -include *.jpg -recurse | sort-object -property directoryname -unique

현재 폴더에 있는 .jpg 파일들 중 20160101 이후에 수정되거나 생성된 파일만 해당 경로로 강제로 복사 (백업시 사용)

get-childitem .\* -recurse -include *.jpg | where-object {($_.lastwritetime -gt 2016-01-01) -and ($_.creationtime -gt 2016-01-01)} | copy-item -destination c:\users\gyurs\downloads\ -force

1.1.5 Get-PSDrive

현재 드라이브 정보를 조회할 수 있다

get-psdrive

1.1.6 Get-Command

특정 명령어의 커맨드 리스트를 보여준다

get-command get-member

form이라는 동사 커맨드가 들어간 커맨드를 찾을 때 사용

get-command -verb *form*

1.1.7 Get-Help

특정 커맨드의 사용법을 알려준다

get-help get-member

Get-Member의 상세한 설명을 확인

get-help get-member -detailed

Get-Member의 모든 설명을 본다

get-help get-member -full

1.1.8 Get-Alias

모든 별칭의 리스트를 볼 수 있다

get-alias

1.1.9 Get-Date

현재의 시간을 출력한다

get-date

시스템이 켜져있는 시간(uptime)을 구한다

(get-date) - (gcim.Win32_OperatingSystem).LastBootUpTime

1.1.10 Get-Item

c:\Windows폴더에 가장 최근 접근한 시간을 보여준다

(get-item C:\Windows).LastAccessTime

c:\Windows\의 모든 파일을 w를 제외하고 보여준다

get-item c:\Windows\*.* -exclude w*

1.1.11 Get-History

지금까지 입력한 command의 목록을 볼 수 있다

get-history

1.1.12 Get-Eventlog

이벤트로그 목록을 확인

get-eventlog -list

이벤트로그를 20160805 이후에 생성된 installer 구문이 들어간 로그를 10개만 확인

get-eventlog -logname application -message *installer* -after 2016-08-05 -newest 10

이벤트로그(6009)로 시스템 부팅 시 발생한 로그를 확인

get-eventlog system | Where-Object {$_.eventid -eq 6009} | more

이벤트로그를 통해 에러가 났던 로그를 확인 (format-table형식으로)

get-eventlog system | Where-Object {$_.entrytype -match "error"} | format-table eventid, source, timewritten -autosize | more

1.1.13 Get-Service

현재 running 상태인 서비스 목록을 확인

(gsv)get-service | where-object {$_.status -eq "running"}

running 서비스 중에서 sql 글자가 들어간 서비스를 검색

get-service | where-object {$_.status -eq "running"} | where Name -like *sql*

sql*로 시작하는 프로세스 중 동작 중인 프로세스를 종료

get-service | where Name -like sql* |where status -eq running | Stop-Service -Force

1.1.14 Get-Appxpackage

파워쉘을 이용해 microsoft EDGE를 설치

get-appxpackage -allusers -name microsoft.microsoftedge | foreach {add-appxpackage -disabledevelopmentmode -register "$($_.installlocation)\appxmanifest.xml-verbose}

Get started 윈도우 10 app을 삭제

get-appxpackage *getstarted* | remove-appxpackage

1.2 Stop-…

1.2.1 Stop-Process

lmgrd 프로세스를 종료하면 어떤 결과가 발생할 지 예측

stop-process -name lmgrd -whatif

lmgrd 프로세스를 종료할 때 확인 프롬프트를 띄운다

stop-process -name lmgrd -confirm

1.3 Set-…

1.3.1 Set-ExecutionPolicy

스크립트 실행 보안을 해제

set-executionpolicy remotesigned

공유폴더에 위치한 서명안된 스크립트를 실행

set-executionpolicy unrestricted

1.4 Export-…, Import-…

1.4.1 Export-CSV, Import-CSV

process 목록을 csv로 저장시킨 후 정렬해서 불러온다

ps | export-csv pslist.csv
import-csv pslist.csv | select-object starttime | sort processname -Descending

1.5 New-…

1.5.1 New-Item

mkdir과 비슷하게 폴더를 만든다

(ni) new-item -type directory -path "path_name"

새로운 txt 파일을 내용을 갖춘채로 만든다

new-item .\new_file.txt -type file -force -value "this is text added to the file"

디렉토리를 만들면 어떤 결과물이 나올지를 확인 

new-item -path c:\ -name dirtest -itemtype directory -whatif

1.6 Remove-…

1.6.1 Remove-Item

alias로 등록되어 있는 get_event를 지운다

remove-item alias::get_event

1.7 .Net framework

1.7.1 [Math]

MATH::POW .net에서 함수를 가져와 2의 3승을 계산한다

[math]::pow(2,3)

2 Powershell 스크립트

2.1 현재 시스템의 실행시간(uptime)을 출력하는 스크립트

# 지정 한 서버의 uptime 을 출력합니다.
param([string] $Machine = ".")

# Win32_OperationSystem 오브젝트를 변수에 저장.
$OS = Get-WmiObject Win32_OperatingSystem -ComputerName $Machine

# 시스템 관리용 시간 값을 일반적인 시간 값으로 변경하여 변수에 저장.
$LastBootUpTime = [System.Management.ManagementDateTimeconverter]::ToDateTime($OS.LastBootUpTime)

# 현재 시간을 구함.
$Now = Get-Date

#Uptime 계산.
$UpTime = $Now - $LastBootUpTime

# 각 값을 계산하여 string 형식으로 변환 후 출력
[string]$UpTime.Days + Days, + [string]$UpTime.Hours + Hours, + [string]$UpTime.Minutes + Minutes."

2.2 현재 자신의 Drive의 용량상태를 GB 단위로 확인하는 스크립트

$disk = Get-WmiObject Win32_LogicalDisk -Filter "DeviceID='C:'| Select-Object Size, FreeSpace
Write-Host ("{0}GB total-f [math]::truncate($disk.Size / 1GB))
Write-Host ("{0}GB free-f [math]::truncate($disk.FreeSpace / 1GB))

3 $ 변수의 활용

3.1 $ 변수

PowerShell 버전을 확인

  • $PSVersionTable

ComputerName 컴퓨터 이름을 확인

  • $env:computername

3.2 예제

  • Script#1
  • $a = 5
    $a.gettype() .net 내장타입을 알 수 있다
    $a.gettype().name .net의 내장타입을 알 수 있다
  • Script#2 (iexplore 프로세스를 여는 예제코드)
  • $ie = new-object -comobject "internetexplorer.application"
    $ie | get-member -membertype method
    $ie.navigate("http://www.naver.com")
    $ie.visible = $true
    
  • Script#3 (%userprofile% 로 이동)
  • cd $env:userprofile
    
  • Script#4 (schtasks에서 ashley 글자가 들어간 예약내용을 확인)
  • $tasks = schtasks.exe /query /fo csv | ConvertFrom-Csv
    $tasks | Where-Object {$_.taskname -like "*ashley*"}
    

3.3 Powershell 함수

3.3.1 Variable Functions

핑을 날려 서버상태를 확인합니다

  • pingsrv "ip_adrress"
function pingsrv ([string] $srv ) {
        $wmiobj=get-wmiobject win32_pingstatus -filter "address='$srv'"
        if($wmiobj.statuscode -eq 0) {
                write-host $srv "연결됐습니다!"
        }
        else {
                write-host $srv 연결이안되네요!"
        }
}

POWERSHELL 프롬프트 형식을 바꿉니다

  • Prompt
function prompt {
        $historyList = @(get-history)
        if($historyList.count -gt 0) {
                $lastcommand = $historyList[$historyList.count - 1]
                $lastid = $lastcommand.id
        }

        write-host ("PS(+ ($lastid+1) + ") + $(get-location) +">") -nonewline
        return "
}