황현동 블로그 개발, 인생, 유우머

151119 파워쉘 스터디

Tags:




파워쉘 교재

http://book.naver.com/bookdb/review.nhn?bid=7206878

돈존스님께 감사를 표하며 배운것을 기반으로 실무에서 바로 쓸수 있게 샘플을 몇가지 짜 봤습니다. 제 입장에선 나중에 이 블로그글 한번 읽어보면 대충 쓸수 있을것 같아서 정리했습니다. 좀더 깊이 파워쉘을 이해하고 싶으신 분들은 꼭 책사서 보세요 후회안합니다.

파워쉘 소개

예전부터 파워쉘을 배워보고 싶었는데 좋은 가이드북이 나와서 쉽게 익혀서 바로 실무에 쓸수 있게 되었습니다. 이제까지 당연히 cmd.exe에서 bat 스크립트 작성해서 빌드배포스크립트 정도 작성해서 사용하고 있었는데 앞으로는 파워쉘로 갈아타야 겠습니다.

파워쉘의 장점

  • bash등 유닉스계열 쉘명령어와 견주어 손색없는 강력한 기능
    • 기존 cmd 명령어들을 전부 지원
    • alias 기능을 통해 자주쓰는 유닉스 스타일 쉘명령어를 사용가능
      • 유닉스 쉘 사용자들 처음 접근할때 거부감 적음
      • ls, cp, mv 등 명령어를 사용할 수 있지만 옵션은 서로 다름.
    • 강력한 파워쉘 도움말
      • 도움말마다 실용적인 예제가 여러개 포함되어 있어서 편함.
      • 개인적으로는 man보다 훨씬 낫다고 생각.
    • 객체기반의 파이프라인 입출력
      • 입력과 출력의 형태가 텍스트 뿐만 아닌 객체(정확히는 닷넷객체)로 아주 명확함.
      • 파이프라인으로 입출력을 연결하는 스크립트를 작성하거나 기존의 명령어, 스크립트를 사용할때 큰 장점.
    • 강력한 파워셀 IDE
      • 강력한 파워쉘 IDE인 power_ise.exe가 파워쉘 설치될때 함께 설치됨.
    • 비주얼스튜디오 연동
      • 최강 IDE인 비주얼스튜디오가 파워쉘을 역시 잘 지원함.
      • 필자는 파워셀을 비주얼스튜디오의 package manager console로 테스트하고, 스크립트도 비주얼 스튜디오로 작성했음.
      • power_ise에서 텍스트 클립보드 복사를 했을때 한글깨지는 문제가 있는데 비주얼 스튜디오에서 작업했을때는 이 버그없음.
    • 닷넷프레임워크와 완벽연동
      • 파워쉘의 커멘드도 좋고 많은 기능이 있고, 이 기능만으로도 대부분의 스크립트는 작성할 수 있지만,
      • 닷넷어셈블리의 모든 기능을 로드해서 사용할 수도 있음.
      • 기존에 사용하던 닷넷 어셈블리의 기능을 스크립트에 바로 연결하는 용도로 유용하게 사용할 수 있겠음.
      • 단순 연결뿐 아니라 스크립트 코드로 복잡한 기능까지 구현가능(약간 VB.NET 느낌)
    • 쉘이 주는 편안함
      • 환경변수, 레지스트리, 서비스제어, 프로세스제어 등 업무를 자동화 할 수 있음.
      • 윈도우는 오히려 GUI때문에 일이 복잡해 지는 경우가 많은데 파워쉘이 이를 편안한 업무가 되도록 해줌.

파워쉘의 단점

  • 약간 느린 느낌
    • 닷넷프레임워크 기반이므로 콜드스타트가 느린 태생적인 특성이 있는것 같음. ( 확실치는 않고 기분탓인가? )
  • more 가 안됨
    • ls | more 와 같이 긴 결과를 나눠서 보는 명령어
    • powershell.exe에서는 잘 동작하는데 powershell_ise.exe 나 비주얼스튜디오에선 안된다.
    • 원인은 모르겠고 엄청불편하다.
  • 가끔 cmd 에선 되던 스크립트가 파워쉘로 가져오니 안되는게 있음.
    • 발견된것 중에 pscp.exe가 그랬는데 옵션이 상당히 길어지니 cmd 에선 되다가 파워쉘에선 안됨.
    • 내 내공이 짧아서 그렇게 된것 같기는 한데 해결은 못했음. (똑같이 쓰면 다 된다면서ㅠㅠ)

파워쉘의 활용

  • 각종 빌드/배포 스크립트
    • 조건이 많이 걸려서 분기가 복잡한 스크립트
    • 기존의 모듈의 일부 기능을 연결하는 경우
  • nuget 관리
    • nuget 명령어는 모두 파워쉘 기반이다.
    • 설치, 업데이트, 삭제 모두 파워쉘로 빠르고 간편하게 제어할 수 있음.
  • 각종 통계처리
    • 엑셀파일, json, xml 편집에 최적화 되어 있음.
    • 일반 텍스트인 경우도 유닉스 쉘만큼은 편하게 되어 있음.

파워쉘버전확인

파워쉘 전역변수들은 $ 입력하면 자동완성으로 대강 확인해 볼수 있음.

PS C:\temp> $PSVersionTable

Name                           Value                                                                                                                                                                                                                                    
----                           -----                                                                                                                                                                                                                                    
PSVersion                      5.0.10240.16384                                                                                                                                                                                                                          
WSManStackVersion              3.0                                                                                                                                                                                                                                      
SerializationVersion           1.1.0.1                                                                                                                                                                                                                                  
CLRVersion                     4.0.30319.42000                                                                                                                                                                                                                          
BuildVersion                   10.0.10240.16384                                                                                                                                                                                                                         
PSCompatibleVersions           {1.0, 2.0, 3.0, 4.0...}                                                                                                                                                                                                                  
PSRemotingProtocolVersion      2.3                                                                                                                                                                                                                                       

명령어 찾기

help는 정말 자주 쓰는 cmdlet인데 주로 이렇게 와일드카드를 섞어서 검색한다.

PS C:\temp> help *log*

Name                              Category  Module                    Synopsis                                                                                                                                                                                          
----                              --------  ------                    --------                                                                                                                                                                                          
Clear-EventLog                    Cmdlet    Microsoft.PowerShell.M... Deletes all entries from specified event logs on the local or remote computers.                                                                                                                   
Get-EventLog                      Cmdlet    Microsoft.PowerShell.M... Gets the events in an event log, or a list of the event logs, on the local or remote computers.                                                                                                   
Limit-EventLog                    Cmdlet    Microsoft.PowerShell.M... Sets the event log properties that limit the size of the event log and the age of its entries.                                                                                                    
New-EventLog                      Cmdlet    Microsoft.PowerShell.M... Creates a new event log and a new event source on a local or remote computer.                                                                                                                     
Remove-EventLog                   Cmdlet    Microsoft.PowerShell.M... Deletes an event log or unregisters an event source.                                                                                                                                              
Show-EventLog                     Cmdlet    Microsoft.PowerShell.M... Displays the event logs of the local or a remote computer in Event Viewer.                                                                                                                        

파라미터로 도움말 보기

help의 결과는 상당히 긴 경우가 많은데 특정한 파라미터에 대한 도움말을 보고자 하면 이렇게도 할 수 있음. 뭐 나중에 까먹으면 스크롤 하면 되는데…

PM> help get-eventlog -Parameter newest

-Newest [<Int32>]
    Specifies the maximum number of events retrieved. Get-EventLog gets the specified number of events, beginning with the newest event in the log.
   
    Required?                    false
    Position?                    named
    Default value                none
    Accept pipeline input?       false
    Accept wildcard characters?  false

알리아스 열거

gal은 알리아스를 전부 얻어오는 cmdlet인데 아래와 같이 기본으로 50여개 정도 미리 정해져 있음. 사실은 gal도 Get-Alias의 알리아스임. 교재에선 알리아스를 적어도 스크립트나 문서작성시에는 사용하지 말고 full name 사용하라고 하는데 나는 편한대로 계속 알리아스 쓸것임.

PS C:\temp> gal

CommandType     Name                                               Version    Source                                                                                                                                                                                    
-----------     ----                                               -------    ------                                                                                                                                                                                    
Alias           % -> ForEach-Object                                                                                                                                                                                                                                     
Alias           ? -> Where-Object                                                                                                                                                                                                                                       
Alias           ac -> Add-Content                                                                                                                                                                                                                                       
Alias           asnp -> Add-PSSnapin                                                                                                                                                                                                                                    
Alias           cat -> Get-Content                                                                                                                                                                                                                                      

테이블 포멧팅

파워쉘은 객체를 리턴하고 아래와 같이 프로세스 객체를 리턴하는 ps 의 결과 출력은 그 모든 속성을 표시하라 결과가 너무 복잡해짐.

PS C:\temp> ps power* | Format-Table id, name

   Id Name         
   -- ----         
10268 powershell_ise
10324 powershell_ise

프로세스에서 연결된 모듈찾기

이런 특수기능은 help를 찾아보고 샘플을 보는게 빠르다. 잘 아는 cmdlet이라도 샘플을 잘 찾아보면 유용한게 많다.

PS C:\temp> ps power* -Module

   Size(K) ModuleName                                         FileName                                                                                                                                                                                                  
   ------- ----------                                         --------                                                                                                                                                                                                  
       264 powershell_ise.exe                                 C:\Windows\System32\WindowsPowerShell\v1.0\powershell_ise.exe                                                                                                                                             
      1796 ntdll.dll                                          C:\WINDOWS\SYSTEM32\ntdll.dll                                                                                                                                                                             
       416 MSCOREE.DLL                                        C:\WINDOWS\SYSTEM32\MSCOREE.DLL                                                                                                                                                                           
       692 KERNEL32.dll                                       C:\WINDOWS\system32\KERNEL32.dll                                                                                                                                                                          
      1908 KERNELBASE.dll                                     C:\WINDOWS\system32\KERNELBASE.dll                                                                                                                                                                        

메모리 100MB 이상 사용하는 프로세스 찾기

where : 좌변의 컬렉션의 일부를 선택하는 필터역할 $_ : 좌변의 한 객체를 가르키며 . 와 붙여서 모든 속성을 접근 할 수 있다. -gt : greater than 즉 > 부등호를 나타낸다.

PS C:\temp> ps | where { $_.WorkingSet -gt 100000000 }

Handles  NPM(K)    PM(K)      WS(K) VM(M)   CPU(s)     Id ProcessName                                                                                                                                                                                                   
-------  ------    -----      ----- -----   ------     -- -----------                                                                                                                                                                                                   
   2214     263    49560     120344 ...47   105.66   8244 explorer                                                                                                                                                                                                      
    821      67   187240     201212  1168     8.94  10268 powershell_ise                                                                                                                                                                                                
    731      64   230608     229580  1066    18.31  10324 powershell_ise                                                                                                                                                                                                

모든 속성을 리스트로 열거

Format-List : 모든속성을 리스트형식으로 열기 속성이 많을경우 기본포멧팅으로는 컬럼이 넘쳐서 일부 속성들을 표시하지 못하는데, 이렇게 리스트포멧팅하면 놓치는 속성이 없이 모두 표시가능.

PS C:\temp> ps winword | Format-List *


__NounName                 : Process
Name                       : WINWORD
Handles                    : 919
VM                         : 526561280
WS                         : 91549696
PM                         : 46804992

레지스트리 접근하기

레지스트릴를 파일시스템과 동일한 방식으로 접근가능하다. si, ri 으로 레지스트리 값을 수정하는 것도 가능하다. 파일, 레지스트리, 환경변수 등이 모두 같은 방식으로 제어 가능함.

PS HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\Advanced> pwd

Path                                                            
----                                                            
HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\Advanced

파일생성

빈파일을 생성하는 cmdlet

PS C:\temp> ni -Name abc.txt -ItemType File


    디렉터리: C:\temp


Mode                LastWriteTime         Length Name                                                                                                                                                                                                                   
----                -------------         ------ ----                                                                                                                                                                                                                   
-a----       2015-09-03   오후 9:12              0 abc.txt                                                                                                                                                                                                                 

명령어 -> 알리아스 찾기

cmdlet을 통해서 alias찾기

PS C:\temp> gal -Definition *item*

CommandType     Name                                               Version    Source                                                                                                                                                                                    
-----------     ----                                               -------    ------                                                                                                                                                                                    
Alias           cli -> Clear-Item                                                                                                                                                                                                                                       
Alias           clp -> Clear-ItemProperty                                                                                                                                                                                                                               
Alias           copy -> Copy-Item                                                                                                                                                                                                                                       
Alias           cp -> Copy-Item                                                                                                                                                                                                                                         

알리아스 -> 명령어 찾기

alias를 통해서 cmdlet찾기

PS C:\temp> gal -Name gal

CommandType     Name                                               Version    Source                                                                                                                                                                                    
-----------     ----                                               -------    ------                                                                                                                                                                                    
Alias           gal -> Get-Alias                                                                                                                                                                                                                                        

파일 쓰기, 읽기, 변수할당, 비교

Out-File : 파일로 쓰기

PS C:\temp> "hello world" | Out-File helloworld.txt

PS C:\temp> "hello great world ps" | Out-File helloworld2.txt

PS C:\temp> $f1 = gc .\helloworld.txt

PS C:\temp> $f2 = gc .\helloworld2.txt

PS C:\temp> diff $f1 $f2

InputObject          SideIndicator
-----------          -------------
hello great world ps =>          
hello world          <=          

서비스목록을 csv파일로 저장

Export-Csv : csv파일로 출력

PS C:\temp> gsv | Export-Csv abc.csv 

csv파일을 출력함

gc : Get-Conentent, 파일을 출력함.

PS C:\temp> gc .\abc.csv

#TYPE System.ServiceProcess.ServiceController
"Name","RequiredServices","CanPauseAndContinue","CanShutdown","CanStop","DisplayName","DependentServices","MachineName","ServiceName","ServicesDependedOn","ServiceHandle","Status","ServiceType","Site","Container"
"AdobeARMservice","System.ServiceProcess.ServiceController[]","False","False","True","Adobe Acrobat Update Service","System.ServiceProcess.ServiceController[]",".","AdobeARMservice","System.ServiceProcess.ServiceController[]","SafeServiceHandle","Running","Win32Own
Process",,

핫픽스 조사, 정렬, 열선택, html로 변환, 파일로 저장

sort : 정해진 속성으로 정렬 select : 표시할 컬럼을 선택 ConvertTo-Html : html로 출력

PM> Get-HotFix | sort InstalledOn | select InstalledOn, InstalledBy, HotfixID | ConvertTo-Html | Out-File abc.html
PM> gc abc.html
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>HTML TABLE</title>
</head><body>
<table>
<colgroup><col/><col/><col/></colgroup>
<tr><th>InstalledOn</th><th>InstalledBy</th><th>HotfixID</th></tr>
<tr><td>2015-08-19 오전 12:00:00</td><td>NT AUTHORITY\SYSTEM</td><td>KB3074678</td></tr>
<tr><td>2015-08-19 오전 12:00:00</td><td>NT AUTHORITY\SYSTEM</td><td>KB3074686</td></tr>
<tr><td>2015-08-19 오전 12:00:00</td><td>NT AUTHORITY\SYSTEM</td><td>KB3081440</td></tr>
<tr><td>2015-08-19 오전 12:00:00</td><td>NT AUTHORITY\SYSTEM</td><td>KB3081441</td></tr>
<tr><td>2015-08-19 오전 12:00:00</td><td>NT AUTHORITY\SYSTEM</td><td>KB3081444</td></tr>
<tr><td>2015-08-19 오전 12:00:00</td><td>NT AUTHORITY\SYSTEM</td><td>KB3087916</td></tr>
<tr><td>2015-08-29 오전 12:00:00</td><td>NT AUTHORITY\SYSTEM</td><td>KB3081452</td></tr>
<tr><td>2015-08-30 오전 12:00:00</td><td>NT AUTHORITY\SYSTEM</td><td>KB3081449</td></tr>
<tr><td>2015-09-01 오전 12:00:00</td><td>NT AUTHORITY\SYSTEM</td><td>KB3081448</td></tr>
<tr><td>2015-09-09 오전 12:00:00</td><td>NT AUTHORITY\SYSTEM</td><td>KB3081455</td></tr>
</table>
</body></html>
PM>

커스톰 컬럼을 출력

PS C:\temp> ps | select @{ l='mycol'; e={$_.Name} }


mycol               
-----               
armsvc              
ccSvcHst            
ccSvcHst            
csrss               
csrss               

커스톰 컬럼, 테이블 포멧팅

ft : 커스톰컬럼을 출력, select와 비교해 봤을때 포멧팅설정을 변경하는 기능추가

PS C:\temp> ps | ft Name, Id, @{l='namelength'; e={$_.Name.Length}} -AutoSize -Wrap


Name                     Id namelength
----                     -- ----------
armsvc                 2884          6
ccSvcHst               3052          8
ccSvcHst               4504          8
csrss                   600          5
csrss                  4468          5

프로세스 인덱스선택, 처음범위선택, 마지막범위선택

select : 좌측컬렉션에서 인덱스 선택

PS C:\temp> ps | select -Index 5


Handles  NPM(K)    PM(K)      WS(K) VM(M)   CPU(s)     Id ProcessName                                                                                                                                                                                                   
-------  ------    -----      ----- -----   ------     -- -----------                                                                                                                                                                                                   
    565      32     2748      23616 ...86    53.23   4468 csrss                                                                                                                                                                                                         



PS C:\temp> ps | select -First 3

Handles  NPM(K)    PM(K)      WS(K) VM(M)   CPU(s)     Id ProcessName                                                                                                                                                                                                   
-------  ------    -----      ----- -----   ------     -- -----------                                                                                                                                                                                                   
    219      13     2468      10768    66     0.30   2884 armsvc                                                                                                                                                                                                        
    186      14     9120      15808 ...42     0.25   9580 audiodg                                                                                                                                                                                                       
   1659      77    38448      15916   256   585.42   3052 ccSvcHst                                                                                                                                                                                                      



PS C:\temp> ps | select -Last 4

Handles  NPM(K)    PM(K)      WS(K) VM(M)   CPU(s)     Id ProcessName                                                                                                                                                                                                   
-------  ------    -----      ----- -----   ------     -- -----------                                                                                                                                                                                                   
    195      14     6224      13348 ...99     9.23   7300 WmiPrvSE                                                                                                                                                                                                      
    234      12     1844       7280 ...94     0.11   1416 WUDFHost                                                                                                                                                                                                      
    236      12     1848       7572 ...91     7.17   1944 WUDFHost                                                                                                                                                                                                      
    323      17     3160      11340 ...36     0.47   2104 WUDFHost                                                                                                                                                                                                      

grep 과 유사

findstr으로 해도 됨.

PS C:\temp> get-alias | out-string -stream | select-string "Get-Command"

Alias           gcm -> Get-Command                

표준적인 필터링

ps ? { $_.Name -like ‘power’ } 도 같은 결과임.
PS C:\temp> ps | ?{$_.Name.Contains('power')}

Handles  NPM(K)    PM(K)      WS(K) VM(M)   CPU(s)     Id ProcessName                                                                                                                                                                                                   
-------  ------    -----      ----- -----   ------     -- -----------                                                                                                                                                                                                   
    984      91   355856     353976  1181   272.64  10268 powershell_ise                                                                                                                                                                                                
    672      63   232728     100708  1062    21.19  10324 powershell_ise                                                                                                                                                                                                  

mac주소 조사

PM> Get-NetAdapter

Name                      InterfaceDescription                    ifIndex Status       MacAddress             LinkSpeed
----                      --------------------                    ------- ------       ----------             ---------
로컬 영역 연결* 6               Juniper Networks Virtual Adapter             14 Up           02-05-85-7F-EB-80         2 Gbps
Wi-Fi                     Intel(R) Dual Band Wireless-AC 7260          11 Up           7C-7A-91-A1-35-88       324 Mbps
Bluetooth 네트워크 연결         Bluetooth 장치(개인 영역 네트워크)                      5 Disconnected 7C-7A-91-A1-35-8C         3 Mbps
VirtualBox Host-Only N... VirtualBox Host-Only Ethernet Adapter         6 Up           0A-00-27-00-00-00         1 Gbps
이더넷                       Intel(R) Ethernet Connection I218-V           9 Disconnected 54-EE-75-07-8C-46          0 bps

네트워크 설정에서 WI-FI 항목만 리스팅

PS C:\temp> Get-WmiObject win32_networkadapterconfiguration | ? {$_.Description.ToLower().Contains('wi-fi')}


DHCPEnabled      : True
IPAddress        :
DefaultIPGateway :
DNSDomain        :
ServiceName      : vwifimp
Description      : Microsoft Wi-Fi Direct Virtual Adapter
Index            : 3

DHCPEnabled      : True
IPAddress        :
DefaultIPGateway :
DNSDomain        :
ServiceName      : vwifimp
Description      : Microsoft Wi-Fi Direct Virtual Adapter
Index            : 4

OS 정보 리스팅

PS C:\temp> Get-WmiObject win32_operatingsystem


SystemDirectory : C:\WINDOWS\system32
Organization    :
BuildNumber     : 10240
RegisteredUser  : hhd2002@hotmail.com
SerialNumber    : 00330-80000-00000-AA030
Version         : 10.0.10240

인증서 상세보기

Cert:\ : 인증서 가상드라이브

PS Cert:\CurrentUser\CA> ls | select -First 1 | fl *


PSPath                   : Microsoft.PowerShell.Security\Certificate::CurrentUser\CA\FF67367C5CD4DE4AE18BCCE1D70FDABD7C866135
PSParentPath             : Microsoft.PowerShell.Security\Certificate::CurrentUser\CA
PSChildName              : FF67367C5CD4DE4AE18BCCE1D70FDABD7C866135
PSDrive                  : Cert
PSProvider               : Microsoft.PowerShell.Security\Certificate
PSIsContainer            : False
EnhancedKeyUsageList     : {}
DnsNameList              : {Symantec Class 3 Secure Server CA - G4}
SendAsTrustedIssuer      : False
EnrollmentPolicyEndPoint : Microsoft.CertificateServices.Commands.EnrollmentEndPointProperty
EnrollmentServerEndPoint : Microsoft.CertificateServices.Commands.EnrollmentEndPointProperty
PolicyId                 :
Archived                 : False
Extensions               : {System.Security.Cryptography.Oid, System.Security.Cryptography.Oid, System.Security.Cryptography.Oid, System.Security.Cryptography.Oid...}
FriendlyName             :
IssuerName               : System.Security.Cryptography.X509Certificates.X500DistinguishedName
NotAfter                 : 2023-10-31 오?A전u 8:59:59
NotBefore                : 2013-10-31 오?A전u 9:00:00
HasPrivateKey            : False
PrivateKey               :
PublicKey                : System.Security.Cryptography.X509Certificates.PublicKey
RawData                  : {48, 130, 5, 56...}
SerialNumber             : 513FB9743870B73440418D30930699FF
SubjectName              : System.Security.Cryptography.X509Certificates.X500DistinguishedName
SignatureAlgorithm       : System.Security.Cryptography.Oid
Thumbprint               : FF67367C5CD4DE4AE18BCCE1D70FDABD7C866135
Version                  : 3
Handle                   : 652727648064
Issuer                   : CN=VeriSign Class 3 Public Primary Certification Authority - G5, OU="(c) 2006 VeriSign, Inc. - For authorized use only", OU=VeriSign Trust Network, O="VeriSign, Inc.", C=US
Subject                  : CN=Symantec Class 3 Secure Server CA - G4, OU=Symantec Trust Network, O=Symantec Corporation, C=US 

PS HOME 디렉토리

PS C:\temp> $PSHOME
C:\Windows\System32\WindowsPowerShell\v1.0

HOME 디렉토리

PS C:\temp> $HOME
C:\Users\Hyundong

출력 인코딩

PS C:\temp> $OutputEncoding


BodyName          : ks_c_5601-1987
EncodingName      : 한국어
HeaderName        : ks_c_5601-1987
WebName           : ks_c_5601-1987
WindowsCodePage   : 949

PS Drive 리스팅

PS C:\> Get-PSDrive

Name           Used (GB)     Free (GB) Provider      Root                                                                                                                                                                                                 CurrentLocation
----           ---------     --------- --------      ----                                                                                                                                                                                                 ---------------
Alias                                  Alias                                                                                                                                                                                                                            
C                 173.81        281.09 FileSystem    C:\                                                                                                                                                                                                                
Cert                                   Certificate   \                                                                                                                                                                                                     CurrentUser\CA
Env                                    Environment                                                                                                                                                                                                                      
Function                               Function                                                                                                                                                                                                                         
HKCU                                   Registry      HKEY_CURRENT_USER                                                                                                                                        SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\Advanced
HKLM                                   Registry      HKEY_LOCAL_MACHINE                                                                                                                                                                                                 
Variable                               Variable                                                                                                                                                                                                                         
WSMan                                  WSMan                                                                                                                                                                                                                            

환경변수 리스팅

PS Env:\> ls

Name                           Value                                                                                                                                                                                                                                    
----                           -----                                                                                                                                                                                                                                    
ALLUSERSPROFILE                C:\ProgramData                                                                                                                                                                                                                           
APPDATA                        C:\Users\Hyundong\AppData\Roaming                                                                                                                                                                                                        
CommonProgramFiles             C:\Program Files\Common Files                                                                                                                                                                                                            
CommonProgramFiles(x86)        C:\Program Files (x86)\Common Files                                                                                                                                                                                                      
CommonProgramW6432             C:\Program Files\Common Files                                                                                                                                                                                                            
COMPUTERNAME                   HHDX1CARBON 

파일명 재귀적인 검색

PS C:\Program Files (x86)> ls c:\ -Recurse -Filter *.ps1 | select -First 5 | select fullname

FullName                                                                                                                       
--------                                                                                                                       
C:\Program Files\Microsoft DNX\Dnvm\dnvm.ps1                                                                                   
C:\Program Files\Microsoft SDKs\Azure\.NET SDK\v2.7\bin\plugins\RemoteAccess\Microsoft.WindowsAzure.ServiceRuntime.Types.ps1xml
C:\Program Files\Microsoft SDKs\Azure\.NET SDK\v2.7\bin\plugins\RemoteAccess\Microsoft.WindowsAzure.ServiceRuntime.Format.ps1xml
C:\Program Files\WindowsPowerShell\Modules\Pester\3.3.5\build.psake.ps1                                                        
C:\Program Files\WindowsPowerShell\Modules\Pester\3.3.5\Pester.Tests.ps1                                                       

서비스 제어 메소드 분석

PS C:\Program Files (x86)> gsv | gm -MemberType Method


   TypeName: System.ServiceProcess.ServiceController

Name                      MemberType Definition                                                                                                                                                                       
----                      ---------- ----------                                                                                                                                                                       
Close                     Method     void Close()                                                                                                                                                                     
Continue                  Method     void Continue()                                                                                                                                                                  
CreateObjRef              Method     System.Runtime.Remoting.ObjRef CreateObjRef(type requestedType)                                                                                                                  
Dispose                   Method     void Dispose(), void IDisposable.Dispose()                                                                                                                                       
Equals                    Method     bool Equals(System.Object obj)                                                                                                                                                   
ExecuteCommand            Method     void ExecuteCommand(int command)                                                                                                                                                 
GetHashCode               Method     int GetHashCode()                                                                                                                                                                
GetLifetimeService        Method     System.Object GetLifetimeService()                                                                                                                                               
GetType                   Method     type GetType()                                                                                                                                                                   
InitializeLifetimeService Method     System.Object InitializeLifetimeService()                                                                                                                                        
Pause                     Method     void Pause()                                                                                                                                                                     
Refresh                   Method     void Refresh()                                                                                                                                                                   
Start                     Method     void Start(), void Start(string[] args)                                                                                                                                          
Stop                      Method     void Stop()                                                                                                                                                                      
WaitForStatus             Method     void WaitForStatus(System.ServiceProcess.ServiceControllerStatus desiredStatus), void WaitForStatus(System.ServiceProcess.ServiceControllerStatus desiredStatus, timespan timeout)

0번째 서비스 검색, 포즈, 시작

PS C:\Program Files (x86)> (gsv | select -Index 0).Stop()
PS C:\Program Files (x86)> (gsv | select -Index 0) | fl


Name                : AdobeARMservice
DisplayName         : Adobe Acrobat Update Service
Status              : Stopped
DependentServices   : {}
ServicesDependedOn  : {}
CanPauseAndContinue : False
CanShutdown         : False
CanStop             : False
ServiceType         : Win32OwnProcess
 
 
PS C:\Program Files (x86)> (gsv | select -Index 0).Start()
PS C:\Program Files (x86)> (gsv | select -Index 0) | fl


Name                : AdobeARMservice
DisplayName         : Adobe Acrobat Update Service
Status              : Running
DependentServices   : {}
ServicesDependedOn  : {}
CanPauseAndContinue : False
CanShutdown         : False
CanStop             : True
ServiceType         : Win32OwnProcess

노트패드 프로젝트 죽이기

PS C:\temp> ps notepad | %{$_.Kill();} 

디렉토리 하위의 모든 텍스트파일을 5줄씩 출력

PS C:\temp>
ls *.txt -Recurse | % {
Write-Host "FullName :"$_.FullName;
gc $_ -Tail 5;
Write-Host "------------------------------------------------------------------------------------";
}
FullName : C:\temp\ConsoleApplication1\ConsoleApplication1\ReadMe.txt

AppWizard uses "TODO:" comments to indicate parts of the source code you
should add to or customize.

/////////////////////////////////////////////////////////////////////////////
------------------------------------------------------------------------------------
FullName : C:\temp\ConsoleApplication2\ConsoleApplication2\ReadMe.txt

AppWizard uses "TODO:" comments to indicate parts of the source code you
should add to or customize.

/////////////////////////////////////////////////////////////////////////////
------------------------------------------------------------------------------------
FullName : C:\temp\jsoncpp-src-0.5.0\jsoncpp-src-0.5.0\doc\readme.txt
The documentation is generated using doxygen (http://www.doxygen.org).
------------------------------------------------------------------------------------
FullName : C:\temp\jsoncpp-src-0.5.0\jsoncpp-src-0.5.0\test\jsonchecker\readme.txt
Test suite from http://json.org/JSON_checker/.

If the JSON_checker is working correctly, it must accept all of the pass*.json files and reject all of the fail*.json files.
------------------------------------------------------------------------------------
FullName : C:\temp\jsoncpp-src-0.5.0\jsoncpp-src-0.5.0\README.txt
    Json::StyledWritter.
- test_complex_01.actual-rewrite: flattened JSON element tree produced by
    jsontest.exe from reading test_complex_01.rewrite.
test_complex_01.process-output: jsontest.exe output, typically useful to
    understand parsing error.
------------------------------------------------------------------------------------

ps1 파일 실행

Set-ExcutionPolish RemoteSigned -Force : 다운로드 받은 스크립트는 사인되어야 실행한다.

PS C:\temp> cat ps.ps1
ps

PS C:\temp> Set-ExecutionPolicy RemoteSigned -Force

PS C:\temp> .\ps.ps1

Handles  NPM(K)    PM(K)      WS(K) VM(M)   CPU(s)     Id ProcessName                                                                                                                                                                                                   
-------  ------    -----      ----- -----   ------     -- -----------                                                                                                                                                                                                   
    111       9     1396       6224    53     0.02   2728 armsvc                                                                                                                                                                                                        
   1542      72    18980      15968   193     7.34   3212 ccSvcHst                                                                                                                                                                                                      
    354      31     5236       2900   113     0.31   5088 ccSvcHst                                                                                                                                                                                                      
    367      36    21024      50748   295     1.53     84 chrome                                                                                                                                                                                                        
    221      24    29320      25920   214     0.92   1140 chrome                                                                                                                                                                                                        
    243      28    55676      63812   290     2.95   2772 chrome                                                                                                                                                                                                        
    281      31    44176      60608   253     2.98   3100 chrome                                                                                                                                                                                                        

사용자에게 값 입력받기 값 출력

PS C:\temp> $myvar = Read-Host "enter myvar"
enter myvar: abc

PS C:\temp> $myvar
abc

화면출력 명령어

PS C:\temp> Write-Verbose "에러"

PS C:\temp> Write-Debug "에러"

PS C:\temp> Write-Output "output"
output

PS C:\temp> Write-Host "host"
host

PS C:\temp> Write-Error "error"
Write-Error "error" : error
    + CategoryInfo          : NotSpecified: (:) [Write-Error], WriteErrorException
    + FullyQualifiedErrorId : Microsoft.PowerShell.Commands.WriteErrorException
 

PS C:\temp> Write-Warning "warning"
경???고?i: warning
 
  PS C:\temp> Write-Host "hello world" -ForegroundColor Yellow
hello world

사용자에게 문자열입력받음, 필터링

PS C:\temp> Read-Host "enter name over 5 char" | ? { $_.Length -gt 5 }
enter name over 5 char: a

PS C:\temp> Read-Host "enter name over 5 char" | ? { $_.Length -gt 5 }
enter name over 5 char: abcdef
abcdef

출력 인코딩 변경

PS C:\WINDOWS\system32> $OutputEncoding



BodyName          : ks_c_5601-1987
EncodingName      : 한N국???어?i
HeaderName        : ks_c_5601-1987
WebName           : ks_c_5601-1987
WindowsCodePage   : 949
IsBrowserDisplay  : True
IsBrowserSave     : True
IsMailNewsDisplay : True
IsMailNewsSave    : True
IsSingleByte      : False
EncoderFallback   : System.Text.InternalEncoderBestFitFallback
DecoderFallback   : System.Text.InternalDecoderBestFitFallback
IsReadOnly        : True
CodePage          : 949




PS C:\WINDOWS\system32> $OutputEncoding = New-Object -TypeName System.Text.UTF8Encoding

PS C:\WINDOWS\system32> $OutputEncoding


BodyName          : utf-8
EncodingName      : Unicode (UTF-8)
HeaderName        : utf-8
WebName           : utf-8
WindowsCodePage   : 1200
IsBrowserDisplay  : True
IsBrowserSave     : True
IsMailNewsDisplay : True
IsMailNewsSave    : True
IsSingleByte      : False
EncoderFallback   : System.Text.EncoderReplacementFallback
DecoderFallback   : System.Text.DecoderReplacementFallback
IsReadOnly        : True
CodePage          : 65001

디스크 용량 조사, 스크립트 만들기, 스크립트 실행

 Get-WmiObject -Class win32_logicaldisk -ComputerName localhost -Filter "drivetype=3" |
    sort -Property DeviceID |
    ft -Property `
        DeviceID, `
        @{l ='FreeSpace(MB)'; e ={$_ .FreeSpace / 1MB -as [ int]}} , `
        @{l ='Size(GB)'; e ={$_ .Size / 1GB -as [ int]}} , `
        @{l ='%Free'; e ={$_ .FreeSpace / $_. Size * 100 -as [int ]}}


PS C:\project\150712_PowerShell3Study> Set-ExecutionPolicy RemoteSigned -Force

PS C:\project\150712_PowerShell3Study> .\get-diskinventory.ps1

DeviceID FreeSpace(MB) Size(GB) %Free
-------- ------------- -------- -----
C:              283910      455    61

스크립트에 입력파라미터 추가

<#
.SYNOPSIS
디스크용량측정 스크립트
.PARAMETER ComputerName
컴퓨터이름
.EXAMPLE
.\get-diskinventory-with-param.ps1 -ComputerName localhost
#>
param
(
    $ComputerName = 'localhost'
)
Get-WmiObject -Class win32_logicaldisk -ComputerName $ComputerName -Filter "drivetype=3" |
    sort -Property DeviceID |
    ft -Property `
        DeviceID, `
        @{l ='FreeSpace(MB)'; e ={ $_ .FreeSpace / 1MB -as [ int]}} , `
        @{l ='Size(GB)'; e ={ $_ .Size / 1GB -as [ int]}} , `
        @{l ='%Free'; e ={$_ .FreeSpace / $_. Size * 100 -as [int ] }}
PM> help .\get-diskinventory-with-param.ps1 -full

NAME
    C:\hhdcommand\PsScripts\get-diskinventory-with-param.ps1
   
SYNOPSIS
    디스크용량측정 스크립트
   
SYNTAX
    C:\hhdcommand\PsScripts\get-diskinventory-with-param.ps1 [[-ComputerName] <Object>] [<CommonParameters>]
   
   
DESCRIPTION
   

PARAMETERS
    -ComputerName <Object>
        컴퓨터이름
       
        Required?                    false
        Position?                    1
        Default value                localhost
        Accept pipeline input?       false
        Accept wildcard characters?  false
       
    <CommonParameters>
        This cmdlet supports the common parameters: Verbose, Debug,
        ErrorAction, ErrorVariable, WarningAction, WarningVariable,
        OutBuffer, PipelineVariable, and OutVariable. For more information, see
        about_CommonParameters (http://go.microsoft.com/fwlink/?LinkID=113216).
   
INPUTS
   
OUTPUTS
   
    -------------------------- EXAMPLE 1 --------------------------
   
    PS C:\>.\get-diskinventory-with-param.ps1 -ComputerName localhost







PM> .\get-diskinventory-with-param.ps1 localhost

DeviceID FreeSpace(MB) Size(GB) %Free
-------- ------------- -------- -----
C:              232616      455    50

줄번호 찍기

PM> gc news.txt -Encoding UTF8 | % {$i=1} {Write-Host $i $_; $i++;}
1 메인 메뉴로 바로가기서브 메뉴로 바로가기본문으로 바로가기
2  황현동
3 99+
4 TV연예
5 스포츠
6 뉴스스탠드
7 날씨
8 09.04(금)
9 구름많음서울30°C
10 구름조금인천28°C
11 흐림수원30°C
12 구름조금대전30°C
13 구름많음청주29°C

텍스트 내부에서 검색

PM> gc news.txt -Encoding UTF8 | sls -Pattern 뉴스 | ft -Property LineNumber, Line

LineNumber Line                                                      
---------- ----                                                      
         6 뉴스스탠드                                                     
        24 주요뉴스                                                      
        28 [카드뉴스] 취업난에 돈 내놓는 청춘들                                     
        53 상식in뉴스 언론사 뉴스 라이브러리 편집이력                                  
        54 뉴스홈                                                       
        65 랭킹뉴스                                                      
        67 뉴스 검색                                                     
        68 뉴스 검색                                                     
       118 문화일보 관련뉴스언론사 페이지로 이동합니다.                                  
       134 가장 많이 본 뉴스                                                
       136 정치경제사회생활/문화가장 많이 본 뉴스 이전가장 많이 본 뉴스 다음                     
       145 가장 많이 본 뉴스 더보기                                            
       167 분야별 주요뉴스                                                  
       186 분야별 주요뉴스 더보기                                              
       187 상식in뉴스 최신호                                                
       189 상식in뉴스 최신호 더보기                                            
       204 이용약관 서비스 안내 뉴스 편집원칙(책임자: 유봉석) 개인정보취급방침 책임의 한계와 법적고지 뉴스 고객센터

재귀적인 파일내용검색

PM> ls -Filter *.txt -Recurse | sls -Pattern "뉴스" | ft Filename, LineNumber, Line -AutoSize

Filename LineNumber Line                                                      
-------- ---------- ----                                                      
news.txt          6 뉴스스탠드                                                     
news.txt         24 주요뉴스                                                      
news.txt         28 [카드뉴스] 취업난에 돈 내놓는 청춘들                                     
news.txt         53 상식in뉴스 언론사 뉴스 라이브러리 편집이력                                  
news.txt         54 뉴스홈                                                       
news.txt         65 랭킹뉴스                                                      
news.txt         67 뉴스 검색                                                     
news.txt         68 뉴스 검색                                                     
news.txt        118 문화일보 관련뉴스언론사 페이지로 이동합니다.                                  
news.txt        134 가장 많이 본 뉴스                                                
news.txt        136 정치경제사회생활/문화가장 많이 본 뉴스 이전가장 많이 본 뉴스 다음                     
news.txt        145 가장 많이 본 뉴스 더보기                                            
news.txt        167 분야별 주요뉴스                                                  
news.txt        186 분야별 주요뉴스 더보기                                              
news.txt        187 상식in뉴스 최신호                                                
news.txt        189 상식in뉴스 최신호 더보기                                            
news.txt        204 이용약관 서비스 안내 뉴스 편집원칙(책임자: 유봉석) 개인정보취급방침 책임의 한계와 법적고지 뉴스 고객센터

텍스트 편집, join, split

PS Env:\> $array = "one", "two", "three";

PS Env:\> $array
one
two
three

PS Env:\> $str = $array -join ","

PS Env:\> $str
one,two,three

PS Env:\> $array2 = $str -split ","

PS Env:\> $array2
one
two
three

문자열 다루기, like

PS C:\WINDOWS\system32> "hello world abc def" -like '*abc*'

True

텍스트파일 필터링후 셀렉트

PM> gc .\news.txt -Encoding UTF8 | ? {$_.Length -gt 10} | select Length, {$_}


Length $_                                                                                                                                                                                            
------ --                                                                                                                                                                                            
    31 메인 메뉴로 바로가기서브 메뉴로 바로가기본문으로 바로가기                                                                                                                                                               
    23 [단독]고소득 자영업자 탈루소득 1兆 돌파                                                                                                                                                                       
    31 세살 꼬마의 죽음에 영국도 문 열었다…난민 수천명 받기…                                                                                                                                                               
    25 ‘묘하게 비슷하네’…제품 표절 기준 아시나요?                                                                                                                                                                     
    21 [카드뉴스] 취업난에 돈 내놓는 청춘들                                                                                                                                                                         
    28 중국 전승절 열병식은 '돈잔치'…총경비 3조8천억원                                                                                                                                                                  
    29 비행기 기내 테이블 세균.. 집 화장실 변기의 12배                                                                                                                                                  

프로세스 리스트 html 로 출력

PS C:\project\150712_PowerShell3Study> ps | select Name, Id, VM, PM | ConvertTo-Html | Out-File "ps-result.html"

PS C:\project\150712_PowerShell3Study> .\ps-result.html

텍스트파일 읽기, 라인넘버, 라인내용 함께 출력

PS C:\hhdcommand\PsScripts> ( help gc -full | Out-String ) -split '\n' | sls Encoding | ft -AutoSize LineNumber, Line

LineNumber Line                                                                                                                
---------- ----                                                                                                                
         9     Get-Content [-Path] <String[]> [-Credential [<PSCredential>]] [-Delimiter [<System.String>]] [-Encoding {Unkno...
        15     Get-Content [-Credential [<PSCredential>]] [-Delimiter [<System.String>]] [-Encoding {Unknown | String | Unico...
        58     -Encoding [<Microsoft.PowerShell.Commands.FileSystemCmdletProviderEncoding>]...                                 

텍스트파일 읽기, 라인넘버, 라인내용 함께 출력, 행내용 커스토마이즈

PS C:\hhdcommand\PsScripts> ( help gc -full | Out-String ) -split '\n' | sls Encoding | ft -Wrap -AutoSize @{l='num'; e={$_.LineNumber}}, Line

num Line                                                                                                                  
--- ----                                                                                                                  
  9     Get-Content [-Path] <String[]> [-Credential [<PSCredential>]] [-Delimiter [<System.String>]] [-Encoding {Unknown |
    Stri                                                                                                                  
 15     Get-Content [-Credential [<PSCredential>]] [-Delimiter [<System.String>]] [-Encoding {Unknown | String | Unicode |
    Byte                                                                                                                  

 60     -Encoding [<Microsoft.PowerShell.Commands.FileSystemCmdletProviderEncoding>]                        

파이프라인을 이용한 입력/출력 처리 스크립트

<#
.EXAMPLE
PS ~> @('a', 'b') | hhd-test-pipeline-script.ps1 | % { Write-Output ($_ + '12345') }
ahello12345
bhello12345
#>
[CmdletBinding() ]
Param
(
    [Parameter(Mandatory =$True, ValueFromPipeline=$True ,ValueFromPipelinebyPropertyName =$True)]
    [string []]$strList
)
BEGIN
{
}
PROCESS
{
    Foreach ($str in $strList)
    {
        Write-Output ( $str + 'hello');
    }
}
PM> help -full .\hhd-test-pipeline-script.ps1

NAME
    C:\hhdcommand\PsScripts\hhd-test-pipeline-script.ps1
   
SYNOPSIS
   
SYNTAX
    C:\hhdcommand\PsScripts\hhd-test-pipeline-script.ps1 [-strList] <String[]> [<CommonParameters>]
   
   
DESCRIPTION
   

PARAMETERS
    -strList <String[]>
       
        Required?                    true
        Position?                    1
        Default value               
        Accept pipeline input?       true (ByValue, ByPropertyName)
        Accept wildcard characters?  false
       
    <CommonParameters>
        This cmdlet supports the common parameters: Verbose, Debug,
        ErrorAction, ErrorVariable, WarningAction, WarningVariable,
        OutBuffer, PipelineVariable, and OutVariable. For more information, see
        about_CommonParameters (http://go.microsoft.com/fwlink/?LinkID=113216).
   
INPUTS
   
OUTPUTS
   
    -------------------------- EXAMPLE 1 --------------------------
   
    PS ~>@('a', 'b') | hhd-test-pipeline-script.ps1 | % { Write-Output ($_ + '12345') }
   
   
    ahello12345
    bhello12345



PM> @('a', 'b') | .\hhd-test-pipeline-script.ps1 | % { Write-Output ($_ + '안녕하세요') }
ahello안녕하세요
bhello안녕하세요