PowerShell 2.0에서 WebRequest 호출

Migel Hewage Nimesha 2024년2월15일
  1. PowerShell 정적 멤버 연산자 ::
  2. PowerShell 2.0에서 WebRequest를 호출하기 위해 WebRequest 클래스로 웹 요청 만들기
PowerShell 2.0에서 WebRequest 호출

PowerShell 버전 3.0부터 HTTP 또는 HTTPS 웹 요청을 보내고 응답을 다시 받기 위해 Invoke-WebRequest cmdlet이 도입되었습니다.

그 전에는 PowerShell 버전 2.0에서 .Net 기본 클래스 라이브러리를 사용하여 웹 요청을 보냈습니다. WebRequestHttpWebRequest 클래스를 모두 이 용도로 사용할 수 있습니다.

PowerShell의 강점은 번거로움 없이 내장 .Net 클래스 및 메서드에 액세스할 수 있다는 것입니다.

PowerShell 정적 멤버 연산자 ::

PowerShell의 가장 중요한 장점은 PowerShell 스크립트 내에서 .Net 클래스에 액세스할 수 있는 기능을 제공한다는 것입니다. 정적 멤버 연산자는 .Net 라이브러리 클래스 내부의 정적 메서드 및 속성을 호출합니다.

DateTime 클래스의 Now 속성에 액세스하고 싶다고 가정해 보겠습니다. 이상적으로는 현재 시스템 날짜와 시간을 반환합니다.

다음과 같이 PowerShell을 사용하여 이 속성을 호출할 수 있습니다.

[datetime]::Now

출력:

PowerShell 정적 멤버 연산자 - 출력

예상대로 현재 날짜와 시간이 인쇄되었습니다.

PowerShell 2.0에서 WebRequest를 호출하기 위해 WebRequest 클래스로 웹 요청 만들기

WebRequest 클래스는 주어진 URI(Uniform Resource Identifier)에 대한 요청을 호출하기 위해 구현된 .NET 기반 추상입니다. .NET 프레임워크의 System.Net 패키지에 있습니다.

다음은 PowerShell에서 웹 요청을 호출하는 구문입니다.

[System.Net.WebRequest]::Create(uri)

여기서 uri는 웹사이트의 URI입니다.

https://google.com에 간단한 GET 요청을 만들어 봅시다.

$req = [System.Net.WebRequest]::Create('https://google.com')

이렇게 하면 추가로 조작할 수 있는 PowerShell $req 개체가 생성됩니다. $req 개체에 사용 가능한 속성과 메서드를 나열할 수 있습니다.

$req | Get-Member

출력:

PowerShell 2.0에서 WebRequest 호출 - 출력 1

GetResponse() 메서드를 사용하여 이 요청에서 응답 개체에 액세스할 수 있습니다.

 $resp = $req.GetResponse()

PowerShell 콘솔 창에 $resp 개체를 씁니다.

PowerShell 2.0에서 WebRequest 호출 - 출력 2

POST 요청을 처리해야 하는 경우 몇 가지 추가 정보와 함께 동일한 절차를 따를 수 있습니다. 이 경우 request 메서드를 POST로 사용해야 합니다.

또한 요청 컨텐츠 유형과 본문을 다음과 같이 구성하여 전달해야 합니다.

$request = [System.Net.WebRequest]::Create('https://abc.com');
$request.Method = "POST";
$request.ContentType = "application/x-www-form-urlencoded";
$bytes = [System.Text.Encoding]::ASCII.GetBytes("name=tony&age=55");
$request.ContentLength = $bytes.Length;

$requestStream = $request.GetRequestStream();
$requestStream.Write( $bytes, 0, $bytes.Length );
$requestStream.Close();
$request.GetResponse();

위의 구현을 사용하여 WebRequest 클래스를 사용하여 POST 요청을 진행할 수 있습니다.

Migel Hewage Nimesha avatar Migel Hewage Nimesha avatar

Nimesha is a Full-stack Software Engineer for more than five years, he loves technology, as technology has the power to solve our many problems within just a minute. He have been contributing to various projects over the last 5+ years and working with almost all the so-called 03 tiers(DB, M-Tier, and Client). Recently, he has started working with DevOps technologies such as Azure administration, Kubernetes, Terraform automation, and Bash scripting as well.