Powershell – Web (FTP) Request, Response
월요일, 07 7월 2010
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 에서도 동일하게 사용 할 수 있다.