336x280(권장), 300x250(권장), 250x250, 200x200 크기의 광고 코드만 넣을 수 있습니다.
# 개체 Get-Member Type type1, type2 ....
# gps | member   == Get-Process | Get-Meber
# 운영체제의 프로세스 개체에서 속성과 메서드만 표시하고 싶은 경우
PS > Get-Process | get-Member -MemberType property, method                                                                                                             


   TypeName: System.Diagnostics.Process

Name                       MemberType Definition                                                             
----                       ---------- ----------                                                             
BeginErrorReadLine         Method     void BeginErrorReadLine()                                              
BeginOutputReadLine        Method     void BeginOutputReadLine()                                             
CancelErrorRead            Method     void CancelErrorRead()                                                 
CancelOutputRead           Method     void CancelOutputRead()                                                
Close                      Method     void Close()                                                           
CloseMainWindow            Method     bool CloseMainWindow()                                                 
Dispose                    Method     void Dispose(), void IDisposable.Dispose()                             
Equals                     Method     bool Equals(System.Object obj)                                         
GetHashCode                Method     int GetHashCode()                                                      
GetLifetimeService         Method     System.Object GetLifetimeService()                                     
GetType                    Method     type GetType()                                                         
InitializeLifetimeService  Method     System.Object InitializeLifetimeService()                              
Kill                       Method     void Kill()                                                            
Refresh                    Method     void Refresh()                                                         
Start                      Method     bool Start()                                                           
ToString                   Method     string ToString()                                                     
....


# 모든 유형의 속성을 표시하고 싶은 경우
PS > Get-Process | get-Member -MemberType properties
Name                       MemberType     Definition                                                                         
----                       ----------     ----------                                                                         
Handles                    AliasProperty  Handles = Handlecount                                                              
Name                       AliasProperty  Name = ProcessName                                                                 
NPM                        AliasProperty  NPM = NonpagedSystemMemorySize64                                                   
PM                         AliasProperty  PM = PagedMemorySize64                                                             
SI                         AliasProperty  SI = SessionId                                                                     
VM                         AliasProperty  VM = VirtualMemorySize64                                                           
WS                         AliasProperty  WS = WorkingSet64                                                                  
Parent                     CodeProperty   System.Object Parent{get=GetParentProcess;}                                        
__NounName                 NoteProperty   string __NounName=Process                                                          
BasePriority               Property       int BasePriority {get;}                                                            
Container                  Property       System.ComponentModel.IContainer Container {get;}                                  
EnableRaisingEvents        Property       bool EnableRaisingEvents {get;set;}                                                
ExitCode                   Property       int ExitCode {get;}             
...


# Users 루트에 잇는 폴더와 파일 객체에 대한 멤버를 확인
# -Hidden 은 숨길 파일도 표시하는 스위치다.
PS > Get-ChildItem -Path /Users -Hidden | Get-Member                                                                                                                           


   TypeName: System.IO.DirectoryInfo

Name                      MemberType     Definition                                                                                                                                 
----                      ----------     ----------                                                                                                                                 
LinkType                  CodeProperty   System.String LinkType{get=GetLinkType;}                                                                                                   
Mode                      CodeProperty   System.String Mode{get=Mode;}                                                                                                              
Target                    CodeProperty   System.Collections.Generic.IEnumerable`1[[System.String, System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85...
Create                    Method         void Create()    


'ⓟrogramming > PowerShell' 카테고리의 다른 글

PowerShell Script - 기초  (0) 2018.06.26
파이프라인 시스템  (0) 2018.06.25
모듈과 스냅인  (0) 2018.06.23
PowerShell Basic  (0) 2018.06.19
PowerShell on mac  (0) 2018.06.11
블로그 이미지

뚱땡이 우주인

,
336x280(권장), 300x250(권장), 250x250, 200x200 크기의 광고 코드만 넣을 수 있습니다.

모듈


모듈은 윈도우 파워셸에서 사용할 수 있는 명령과 다른 항목을 패키지(어셈블리)로 만들어 제공하거나 스크립트에서 정의할 수 있다.

# 가져온 모듈 확인
Get-Module

# 가져올 수 있는 모듈 확인
Get-Module -ListAvailable

# DnsClient 모듈의 파워셸 명령 목록
Get-Command -Module DnsClient

# DNS 레코드 조회
Resolve-DnsName -Name www.microsoft.com

# HelloModule 이라는 동적 모듈 생성
New-Module -ScriptBlock {function HelloModule {"Hello Module World!"}}

PS > HelloModule



스냅인 (PSSnapin)


파워셸 명령과 공급자를 구현한 동적 링크 라이브러리(dll)

스냅인은 .NET 언어로 작성하고 어셈블리로 패키징해서 InstallUtil.exe로 설치한다.

설치한 이후에 해당 스냅인의 명령어와 공급자를 윈도우 파워셸 세션에 추가해서 사용하면 된다.





# 현재 세션에 추가되었거나 시스템에 등록된 윈도우 파워셸 스냅인을 검색
Get-PSSnapin

# 등록된 파워셸 스냅인을 현재 세션에 추가
Add-PSSnapin

# 스냅인 제거
Remove-PSSnapin

'ⓟrogramming > PowerShell' 카테고리의 다른 글

PowerShell Script - 기초  (0) 2018.06.26
파이프라인 시스템  (0) 2018.06.25
개체 (Object)  (0) 2018.06.23
PowerShell Basic  (0) 2018.06.19
PowerShell on mac  (0) 2018.06.11
블로그 이미지

뚱땡이 우주인

,
336x280(권장), 300x250(권장), 250x250, 200x200 크기의 광고 코드만 넣을 수 있습니다.
◆ 파워셸 명령의 기본 형식

동사-명사

Get-Service -Name w32time
 : w32time이라는 서비스와 관련된 정보를 반환
 == gsv w32time

Get은 파워셸의 기본 동사이므로, Get- 을 생략하고 명사 부분만 바로 입력해서 실행 가능함
 : Get-Help == Help

◆  Alias
PS /Users/hongkun> get-alias -Definition Get-ChildItem                                                                 

CommandType     Name                                               Version    Source                                  
-----------     ----                                               -------    ------                                  
Alias           dir -> Get-ChildItem                                                                                  
Alias           gci -> Get-ChildItem 

기존의 DOS 표준 명령어(cd, dir...)은 모두 파워셸 명령의 별칭이다.

dir, gei 도 모두 결국 Get-ChildItem 의 별칭이다.


Get-Alias 

현재 세션의 전체 별칭 목록 또는 특정 별칭 목록을 보여줌

New-Alias

사용자 지정 별칭을 만듬. 기본적으로 현재 세션이나 원도우 파워셸 실행 중에만 유효하다.

Set-Alias

현재 세션에서 파워셸 명령이나 다른 명령 요소에 대한 별칭을 만들거나 해당 별칭이 없는 경우 변경한다.

Export-Alias

현재 정의된 별칭 정보를 지정한 파일로 내보내기 한다. 기본 값은 csv 파일 형식이며, 스크립트 파일로 내보낼 수 있다. (-As script)

Import-Alias

별칭 파일에서 현재 세션으로 별칭을 가져온다. 이미 있는 경우에 강제로 덮어쓰고 싶은 경우 -Force 옵션을 사용한다.


※ 별칭 삭제 : Remove-Item
 - 별칭의 삭제를 위한 명령이 없고 별칭을 별도의 저장소에 넣고, 저장소를 다루는 명령으로 처리하도록 한다.

// 화면에 출력하는 파워셸 명령인 Write-Output의 새로운 별칭 wo를 만든다.
PS /Users/hongkun> New-Alias -Name wo -Value Write-Output        

// Write-Output 기존 별칭을 wo 에서 wop로 변경한다.                                                                                                                    
PS /Users/hongkun> Set-Alias -Name wop -Value Write-Output

// 지정한 위치에 현재 세션의 별칭 목록을 MyAlias.csv라는 파일로 내보낸다.
PS /Users/hongkun> Export-Alias -Path /Users/hongkun/MyAlias.csv 

// csv 파일 내용
"wo","Write-Output","","None"
"wop","Write-Output","","None"

// 파일에서 별칭 목록 가져오기
PS /Users/hongkun> Import-Alias -Path  /Users/hongkun/MyAlias.csv 

◆ PowerShell 도움말

도움말 업데이트   

PS /Users/hongkun> Update-Help

// 여러 언어와 지역의 도움말 파일을 다운로드
PS /Users/hongkun> Update-Help -UICulture ko-KR, en-US

PS /Users/hongkun> Get-Help -Name New-Alias -Full

 

Get-Help -Name [-detailed | -examples | -full | -online]


PS /Users/hongkun> Get-Help -Name New-Alias -Full                                                                                                                                    

NAME
    New-Alias
    
SYNTAX
    New-Alias [-Name]  [-Value]  [-Description ] [-Option {None | ReadOnly | Constant | Private | AllScope | Unspecified}] [-PassThru] [-Scope ] [-F
    orce] [-WhatIf] [-Confirm]  []
    
    
PARAMETERS
    -Confirm
        
        Required?                    false
        Position?                    Named
        Accept pipeline input?       false
        Parameter set name           (All)
        Aliases                      cf
        Dynamic?                     false
매개변수 종류
  • 필수 매개변수: 명령에 반드시 매개변수와 값을 제공
  • 위치 매개변수: 따로 매개변수명을 입력하지 않고 값만 제공하더라도 해당 값이 제공된 위치에 따라 매개변수를 자동으로 인식 [-Name] 처럼 매개변수명만 대괄호로 감싼 형식으로 표시
  • 선택 매개변수: 필요에  따라 선택적으로 사용, 대괄호로 감싼 경우
  • 스위치: 값이 필요하지 않고 매개변수 이름을 단독으로 사용
New-Alias 매개변수 종류
  • Name은 필수 매개변수이지만 매개변수 이름은 생략하고 값만 제공할 수 있는 위치 매개변수
  • Description은 선택 매개변수이며, 이 매개변수를 선안하면 반드시 값을 제공 [-Description ] <String>
  • -Confirm 와 -WhatIf 는 값을 제공하지 않는 스위치

파워셀 명령을 찾고 빠르게 익히는 방법

-Verb 에는 동사를 -Noun에는 명사 부분을 찾을 수 있음
PS /Users/hongkun> Get-Command -Verb Get* -Noun PS*                                                                                                                                  

CommandType     Name                                               Version    Source                                                                                                
-----------     ----                                               -------    ------                                                                                                
Function        Get-PSCurrentConfigurationNode                     0.0        PSDesiredStateConfiguration                                                                           
Function        Get-PSDefaultConfigurationDocument                 0.0        PSDesiredStateConfiguration                                                                           
Function        Get-PSMetaConfigDocumentInstVersionInfo            0.0        PSDesiredStateConfiguration                                                                           
Function        Get-PSMetaConfigurationProcessed                   0.0        PSDesiredStateConfiguration                                                                           
Function        Get-PSRepository                                   1.6.0      PowerShellGet                                                                                         
Function        Get-PSTopConfigurationName                         0.0        PSDesiredStateConfiguration                                                                           
Cmdlet          Get-PSBreakpoint                                   3.1.0.0    Microsoft.PowerShell.Utility                                                                          
Cmdlet          Get-PSCallStack                                    3.1.0.0    Microsoft.PowerShell.Utility                                                                          
Cmdlet          Get-PSDrive                                        3.1.0.0    Microsoft.PowerShell.Management                                                                       
Cmdlet          Get-PSProvider                                     3.1.0.0    Microsoft.PowerShell.Management                                                                       
Cmdlet          Get-PSReadlineKeyHandler                           1.2        PSReadLine                                                                                            
Cmdlet          Get-PSReadlineOption                               1.2        PSReadLine                                                                                            
Cmdlet          Get-PSSession                                      6.0.2.0    Microsoft.PowerShell.Core                                                                             
◆ PowerShell Version 확인
PS /Users/hongkun> $PSVersionTable                                                                                                      

Name                           Value                                                                                                   
----                           -----                                                                                                   
PSVersion                      6.0.2                                                                                                   
PSEdition                      Core                                                                                                    
GitCommitId                    v6.0.2                                                                                                  
OS                             Darwin 17.3.0 Darwin Kernel Version 17.3.0: Thu Nov  9 18:09:22 PST 2017; root:xnu-4570.31.3~1/RELEAS...
Platform                       Unix                                                                                                    
PSCompatibleVersions           {1.0, 2.0, 3.0, 4.0...}                                                                                 
PSRemotingProtocolVersion      2.3                                                                                                     
SerializationVersion           1.1.0.1                                                                                                 
WSManStackVersion              3.0  
PS /Users/hongkun> Get-Host | Select-Object Version                                                                                     

Version
-------
6.0.2  



◆ 프로세스 목록 확인
PS /Users/hongkun> Get-process                                                                                                          

 NPM(K)    PM(M)      WS(M)     CPU(s)      Id  SI ProcessName                                                                         
 ------    -----      -----     ------      --  -- -----------                                                                         
      0     0.00       0.00       0.00       0 451                                                                                     
      0     0.00       0.00       0.00       1   1                                                                                     
      0     0.00       0.00       0.00      59  59    
...
      0     0.00       4.56       5.31     481 481 VTDecoderXPCSer                                                                     
      0     0.00       4.37       5.43    4309 309 VTDecoderXPCSer                                                                     
      0     0.00       9.39      16.53    1204   1 webinspectord                                                                       
      0     0.00      12.21      38.68     499   1 WiFiAgent                                                                           
      0     0.00      10.91      16.03     422 422 WiFiProxy                                                                           
      0     0.00      10.50       5.24    5024 024 XprotectService


'ⓟrogramming > PowerShell' 카테고리의 다른 글

PowerShell Script - 기초  (0) 2018.06.26
파이프라인 시스템  (0) 2018.06.25
개체 (Object)  (0) 2018.06.23
모듈과 스냅인  (0) 2018.06.23
PowerShell on mac  (0) 2018.06.11
블로그 이미지

뚱땡이 우주인

,