원격지의 서버에 Powershell Remote를 활성화 시키는 작업중 해당 네트워크가 80번 포트를 제외한 거의 모든 포트가 윈도우즈 방화벽이 아닌 네트워크 상에서 막혀 있었다. 즉 Default port 인 5985 / 5986 을 사용 할 수 없어 원격 접속이 불가능한 경우 였다. 이때 포트를 직접 80번으로 바꾸어 주었는데 WSMan:localhostServiceEnableCompatibilityHttpListener 를 활성화 시키면 자동으로 80번 포트가 추가로 사용 가능…
Category Archives: Powershell Tips
Useful Powershell tips
Powershell – 원격 접속을 위한 Credential 만들기
원격 접속을 위해 Enter-PSSession 또는 Invoke-Command 를 수행 할 때 -Credential 파라메터가 필요하다. 사용자 이름만 적으면 자동으로 대화 상자가 뜨면서 입력 할 수 있다.
1 |
Enter-PSSession -ComputerName [대상] -Credential [대상의 사용자] |
직접 Password 를 입력 할 수 없고 대화상자가 뜨는 이유는 -Credential 파라메터에 PSCredential 타입의 개체가 필요한데 이것을 만드는데 사용되는 SecureString 개체가 대화상자를 통해서만 만들수 있다. SecureString 만들기 아래와 같이 직접…
Powershell – Remoting (원격 접속)
원격지에 있는 Powershell 에 접속이 가능하다 정확히는 Session 을 만들수 있는데 이 Session을 이용하여 원격지에 있는 Powershell 과 상호작용이 가능한것이다. 자주쓰게 되는 기능인데 물어보는 분들이 많아 정리 해 둔다. 자세한 규칙이나 프로토콜, 원리등을 설명하면 20페이지정도 문서가 나올꺼 같지만 여기선 필요한 과정들에 대한 설명만 기록한다. 바쁜사람들은 아래를 보고 따라하자. A 가 B 에 원격 접속 하고…
Powershell – Ping-MultipleTarget
ICMP 패킷을 이용하여 Ping 결과를 bool 로 리턴하는 Function을 작성하고, 이를 이용하여 지정된 범위 의 모든 주소에 Ping을 시도하여 Host들의 상태를 확인 한다.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
param ( [Parameter(Mandatory=$true)] $BaseIp, $Start = 1, $End = 255, $Timeout = 100 ) Function Ping-Target { param ( [Parameter(Mandatory=$true)] [string]$HostNameOrAddress, [int]$Timeout = 100 ) $pingObject = New-Object System.Net.NetworkInformation.Ping $pingReply = $pingObject.Send($HostNameOrAddress, $Timeout) return $pingReply.Status -eq [System.Net.NetworkInformation.IPStatus]::Success } $Start..$End | %{ $BaseIp + $_ } | %{ if ($(Ping-Target $_ $Timeout)) { Write-Host $($_ + " .. Success") -ForegroundColor Green } else { Write-Host $($_ + " .. Fail") -ForegroundColor Red } } |
…
Powershell – Resize Powershell Window size
Powershell 창을 사용 할 때 가끔 폭이 너무 작아 불편 할 때가 있다. Height는 창을 늘리면 늘어 나지만 Width는 특정 크기 이상 최대화를 해도 늘어 나지 않는다. Property가 많은 개체를 열어 보거나 긴 text line을 봐야 하는 경우 갑갑 하기도 하다. 이때는 $Host.UI.RawUI.WindowSize 값을 조절 해 줌으로써 넓은 화면을 사용 할 수 있다. 단 변경할때…
Powershell – Invoke-BatchCommand
일반 cmd 에서 잘 수행되던 명령이 Powershell 에서 똑같이 입력 했을 때 오류가 나는 경우가 있다. 대부분 특수문자가 있을때 Powershell이 특수 문자를 특정 연산자로 인식하면서 의도하지 않은 동작이 일어나는 경우 이다. 예를 들어 svn Dump file을 load하는 경우 다음과 같은 명령을 사용한다.
1 |
svnadmin load C:svntest < .test.Dump |
cmd 에서는 잘 실행되지만 Powershell 에서는 다음과 같은 Error가 날 것이다. ‘…
Powershell – Resize Image Files
Powershell 로 이미지 파일을 Resize 해 보자. Parameter는 입력 파일 경로, 출력 파일 경로 그리고 Width, Height 사이즈만 있으면 된다. System.Drawing을 사용하였는데 기본적으로 Load 되어 있는 Assembly가 아니므로 Load 해 줘야 한다. 아래는 여러가지 방법중 하나 이다. .Net 을 사용한 Image Resize 코드들을 찾아 보면 여러 가지 방법이 있으니 다른 방법도 Powershell로 다시 써보면 재미…
Powershell – Customize prompt
Powershell 의 Prompt는 기본적으로 PS {현재경로}> 로 되어 있다. 이 모양은 Powershell 에서 명령을 수행하고 Prompt 라는 Function을 수행한 결과이다. 믿기지 않는 다면 다음 명령으로 확인 해 보자.
1 |
Get-Command prompt |
다음과 같이 Fuction임을 확인 할 수 있을 것이다.
1 2 3 |
CommandType Name Definition ----------- ---- ---------- Function prompt $(if (test-path variable:/PSDebugCon... |
Definition을 자세히 보면 다음과 같다.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
$( if (test-path variable:/PSDebugContext) { '[DBG]: ' } else { '' } ) + 'PS ' + $(Get-Location) + $( if ($nestedpromptlevel -ge 1) { '>>' } ) + '> ' |
위의 코드가 Powershell의 Prompt를 쓰는 것이다. 그러므로 똑같은 이름의 Prompt Function을…
Powershell – FTP List Parsing
Powershell 을 이용해 FTP Server를 상대로 자동화 작업을 하다보니 File 업로드, 다운로드 뿐 만 아니라. 특정 FTP 경로 아래에 있는 File 과 Directory 들의 정보가 필요 했다. 이때 FTP Server를 상대로 WebRequest를 보내는데 이때 Request Method를 “List”로 한다. 이전에 올린 포스트인 Get-WebResponseString 을 이용하여 List를 요청 해 보자. 참고 Get-WebResponseString
1 2 3 4 5 6 7 |
$Url = "ftp://Use-Powershell.com" $Username = "talsu" $Password = "pass1234" $credential = New-Object System.Net.NetworkCredential @($Username, $Password) Get-WebResponseString -Url $Url -Credential $credential -Method "List" |
다음과 같은 결과가 나온다…
Powershell – Web (FTP) Request, Response
Powershell 을 이용하여 웹 요청을 해보자. 웹 사이트를 관리 하거나 Rest 방식의 서비스를 사용 할 때 유용하다. Get-WebResponseString
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
Function Get-WebResponseString { param ( [Parameter(Mandatory=$true)] [String]$Url, [Parameter(Mandatory=$true)] [String]$Method, [Parameter(Mandatory=$false)] [System.Net.NetworkCredential]$Credential ) $Request = [System.Net.WebRequest]::Create($Url) $Request.Method = $Method if ($Credential -ne $null) { $Request.Credentials = $credential } $Response = $Request.GetResponse() $StreamReader = New-Object System.IO.StreamReader $Response.GetResponseStream() $StreamReader.ReadToEnd() } |
사용 예
1 2 3 4 5 6 7 |
$Url = "http://Use-Powershell.com" $Username = "talsu" $Password = "pass1234" $credential = New-Object System.Net.NetworkCredential @($Username, $Password) Get-WebResponseString -Url $Url -Credential $credential -Method "GET" |
$Response 에서 결과 String을 반환 하지 않고 .StatusCode 등 다른 정보를 활용 할 수 있다. Web 뿐만 아니라 FTP 에서도 동일하게 사용 할 수 있다…