All Articles

Getting HTTP Responses by Referencing .NET Framework Objects from PowerShell

This page has been machine-translated from the original page.

PowerShell and .NET Framework

PowerShell is a powerful shell developed as open source that runs on Windows, Linux, and macOS, and is a script language designed as an object-oriented language.

PowerShell is based on the .NET Framework.
Commands, which are equivalent to commands in Bash and other shells, are called cmdlets, but their actual substance is .NET Framework objects.

Like shells used on Linux and elsewhere, it is possible to pass processing results using pipes, but the information passed is not text but .NET Framework objects.
Therefore, flexible and powerful processing can be realized.

In the next section, we will actually load .NET Framework objects from PowerShell.

Referencing System.Net.WebClient

For example, just by executing the following script in PowerShell, the $content variable will contain the HTTP response from the specified URL.

Add-Type -AssemblyName System.Net.Http
$webClient = New-Object System.Net.Http.HttpClient
$content = $webClient.GetAsync("https://kashiwaba-yuki.com")

Specifically, first we use the Add-Type cmdlet, which can define .NET Framework classes, to reference the System.Net.Http class.
Next, we store an instance of the System.Net.Http class in $webClient and use the GetAsync method to retrieve the HTTP response from the specified URL.

When we actually output this $content, the following results were confirmed.

$content

Result                 : StatusCode: 200, ReasonPhrase: 'OK', Version: 1.1, Content: System.Net.Http.StreamContent, Headers:
                         {
                           Transfer-Encoding: chunked
                           Connection: keep-alive
                           Link: https://kashiwaba-yuki.com/wp-json/; rel="https://api.w.org/"
                           Vary: Range
                           Vary: Accept-Encoding
                           X-Cache: MISS
                           Date: Wed, 01 Jul 2020 07:38:37 GMT
                           Server: Apache
                           X-Powered-By: PHP/7.4.4
                           Content-Type: text/html; charset=UTF-8
                         }
Id                     : 365
Exception              :
Status                 : RanToCompletion
IsCanceled             : False
IsCompleted            : True
CreationOptions        : None
AsyncState             :
IsFaulted              : False
AsyncWaitHandle        : System.Threading.ManualResetEvent
CompletedSynchronously : False

Summary

So I’ve summarized that you can reference .NET Framework objects from PowerShell.

Being able to reference .NET Framework objects means that, to put it extremely, what you can do with C# can also be implemented in PowerShell.
Since you can call C# programs from PowerShell, you might not need to write everything in PowerShell…

References