PowerShell
= Object-based Shell 이다
(Object = Property + Method)
PowerShell의 장점
• cmd.exe에서 사용하는 거의 모든 명령어를 사용 가능하다
• 강력한 Pipeline 기능
• 도움말이 탁월하다
• 하나의 명령어를 알게 되면 연관 명령어를 쉽게 찾을 수 있다
• GUI에 비하여 내용을 구체적으로 확인 및 상세히 설정 가능하다
• 반복 작업에 유용하다
• Group Policy를 통하여 PowerShell Script도 적용할 수 있다
• 원하는 cmdlet이 없는 경우에 Script를 만들어 사용할 수 있다
• Function, Module 등을 사용자가 필요에 따라서 생성할 수 있다
• 원격관리 기능이 탁월하다
• CLI 기반의 관리 작업 : GUI는 작업 속도가 느리고 세부적인 정보를 확인하는데 한계가 있고 원격 작업 시 방화벽을 통과하지 못할 수도 있다
- cmdlet : powershell 명령어
- module : cmdlet 모음
Get-Module -ListAvailable : 사용 가능한 모듈 목록 출력
Import-Module -Name activedirectory : activedirectory 관련 모듈을 임포트(임포트해야 사용 가능)
Get-Command -Module activedirectory : activedirectory 모듈의 사용가능한 cmdlet 출력
- 특정 단어와 관련된 cmdlet 찾기
Get-Command (줄여서 gcm) 이용
Get-Command *address* : address 관련 명령어 찾기
gcm *ip* : ip 관련 명령어 찾기
Get-Command -CommandType application | Where-Object {$_.name -like "*.exe"}
: type이 application 인 것 중에 .exe가 들어가는 명령어 찾기
- 명령어가 기억 안날 때 도움받는 법
Help, -examples 옵션 활용하기
** 항상 Help 기능을 최신으로 유지한다 : Update-Help
Get-Help -Name cmdlet
줄여서 >> Help -Name cmdlet
줄여서 >> Help cmdlet
Help *서비스*
Help cmdlet -Examples : 예시 문장을 볼 수 있음
Examples 이외의 또 다른 옵션들
-Full
-Detailed
-Parameter ComputerName
-Online
-ShowWindow
- Windows Feature 확인하고 설치하기
Get-WindowsFeature -Name *powershell*
Install-WindowsFeature -Name PowerShell-v2 -IncludeManagementTools

** 역할 및 기능을 설치할 때는 습관적으로 -IncludeManagementTools 와 -IncludeAllSubfeature 매개변수를 사용하는 게 좋다.
- cmdlet마다 Property와 Method를 확인해야 한다. (확인 방법 : cmdlet | Get-Member)
get-service | get-member
get-process | get-member
- 특정 서비스의 Property 내용 보기
(get service -Name bits).status
get-service | Where-Object {$_.status -eq "stopped"}
: Where-Object는 필터링. $_는 오브젝트 하나하나. 그 중에 status가 stopped인 서비스만 보여달라
- 각 cmdlet의 property 값 확인
: Property와 그 값까지 보고싶으면 fl * 사용
cmdlet | fl *
cmdlet | Format-List *
- Method 실행하기
(Get-Service -name bits).start() : 서비스 시작
(Get-Service -name bits).stop() : 서비스 중지
(Get-Date).Adddays(100) : 100일 후 날짜 알아보기
get-process -name notepad | Stop-Process -Force : 강제 종료
- 정렬하여 확인 가능
sort-object 이용
get-hotfix : 업데이트 확인
get-hotfix | sort-object -property = installedon : 설치된 날짜 순으로 정렬하여 보여달라
(get-hotfix | sort-object -property installedon)[-1] : 제일 마지막으로(최신에) 설치된 항목
- 특별히 WinRM 서비스 5985, 5986 포트를 사용하여 원격 관리를 하므로, 방화벽 관리가 쉬움
>> 원격 컴퓨터 내용보기
1. enter-pssession : 아예 원격 컴퓨터로 들어감
2. invoke-command(줄여서 icm) : 작업하고 빠져나옴
enter-pssession -computername sea-dc1
enter-pssession -cn sea-dc1
Invoke-Command -cn sea-dc1 {dir c:\ }
Invoke-Command -cn sea-dc1 {Restart-Computer -Force} : 강제 재시작
Invoke-Command -cn sea-svr1, sea-svr2 {Install-WindowsFeature -Name telnet-client} : 텔넷 서비스를 두대의 컴퓨터 동시에 설치
- 기존의 Windows 명령어를 그대로 사용할 수 있음
Net users, route, ipconfig, ping, fsutil.exe, netdom.exe 등
- Pipeline과 Script를 적절히 사용하면 시스템을 강력하게 관리 가능
Get-ChildItem -Path c:\ -Filter *.png -Recurse | Copy-Item -Destination e:\backup : c드라이브에서 png 파일을 찾아서 e드라이브에 복사
- Scripting 환경 제공
: 반복적으로 해야 할 작업이나 자동화 해야 할 작업에 적합하다.

- 반복 작업
ex) 사용자 계정을 1000개 생성할 때
ex) File Server의 특정한 폴더를 1주일에 한 번씩 Copy 또는 Backup할 때


Import-Csv -path ~ | new-aduser 명령어로 1초만에 users 추가 가능

- 한꺼번에 여러 개의 데이터를 수정
ex) 부서 이름을 한꺼번에 수정한다
Get-ADUser -Filter {department -eq “Sales”} | Set-ADUser -Department “Sales1”
- 일상적인 작업을 신속하게 처리
ip구성정보 확인
Get-NetIPConfiguration (줄여서 gip)
- 공유폴더 목록 확인
Get-SmbShare
- 특정 프로그램 종료
Get-Process -Name chrome | Stop-Process -Force
- 원격 관리 기능이 탁월
ex) 10대의 컴퓨터의 최신 보안패치 현황을 확인하기
Invoke-Command -ComputerName (Get-Content c:\computers.txt){(Get-Hotfix | Sort-Object -Property InstalledOn)[-1]}
ex) 10대의 컴퓨터에서 컴퓨터 부팅시 자동으로 시작해야 할 서비스가 시작되지 않은 것들만 찾아서 자동으로 서비스 시작하기
Invoke-Command -cn (Get-Content c:\computers.txt) {Gwmi Win32_Service | Where{$_.State -ne "Running" -and $_.Startmode -eq "Auto"} | Start-Service -PassThru}
ex) 여러 개의 원격 컴퓨터에 현재 로그온한 사용자를 확인
Invoke-Command -ComputerName (Get-Content C:\computers.txt) {quser.exe}
ex) 업무시간에 직원들이 Gom Player를 사용하고 있는지 확인
Invoke-Command -ComputerName Server1, Server2, Server3 {Get-Process -Name Gom}
- Script 파일을 Group Policy로 적용할 때 유용
: 도메인의 구성원 컴퓨터 1000대에 동일한 작업을 하고자 하면 '.ps1파일'을 생성하여 Startup Script에 추가하면 사용자가 로그인 하기 전에 모두 작업이 완료된다.

- EventLog 확인하기
Get-EventLog -LogName Application -EntryType Error -After (Get-Date).AddDays(-2)
: 2일 전부터 오늘까지 발생한 이벤트 정보 중에서 Error 만을 확인한다.
- Alias 활용하기
Get-Alias -Definition Get-EventLog : Alias 확인.(없음)
Set-Alias -Name event -Value Get-EventLog : alias 설정
Export-Alias c:\Labfiles\AddedAlias.txt

Import-Alias를 하면 새로운 콘솔을 띄울 때마다 설정해놓은 alias를 사용할 수 있다.
** 콘솔을 실행할 때마다 Import-Alias를 하는게 귀찮다면 Profile을 활용하여 Alias를 사용할 수 있다.
mkdir $home\Documents\WindowsPowershell 폴더를 다음과 같은 위치에 만들어 profile.ps1를 작성한다
# profile.ps1
Import-Alias -Path \\SEA-ADM1\Labfiles\AddedAlias.txt
Write-Host "Alias is successfully loaded"
이제 새로운 PowerShell 콘솔을 띄우면 정상적으로 Alias 사용이 가능하다.
'Study' 카테고리의 다른 글
WEB/WAS 취약점 진단 참고 - WebtoB (1) | 2023.10.27 |
---|---|
커버로스(Kerberos) (0) | 2023.08.29 |
Windows Powershell(2) (0) | 2022.08.05 |
Puzzing 기본 (0) | 2021.04.07 |