Skip to content

Instantly share code, notes, and snippets.

@IISResetMe
Last active March 15, 2022 13:09
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save IISResetMe/2c930a62b93e3e095a28 to your computer and use it in GitHub Desktop.
Save IISResetMe/2c930a62b93e3e095a28 to your computer and use it in GitHub Desktop.
Missing netcat -l in PowerShell
<#
.Synopsis
Registers a HTTP prefix and listens for a HttpRequest
.DESCRIPTION
Simple PowerShell HTTP Server implementation to respond to a single HTTP request
.EXAMPLE
Get-HttpRequest -UriPrefix "http://+:80/TestUri/" -ResponseData (Get-Content C:\inetpub\wwwroot\index.html)
.EXAMPLE
Get-HttpRequest -UriPrefix "http://127.0.0.1/" -ResponseData "It Works...!" -ShowRequest
#>
function Get-HttpRequest
{
[CmdletBinding()]
param (
[Parameter(Mandatory)]
[string]
$UriPrefix,
[Parameter(ValueFromPipeline)]
[string[]]
$ResponseData,
[System.Text.Encoding]
$Encoding = [System.Text.Encoding]::ASCII
)
begin{
Write-Verbose "Creating HttpListener"
$Listener = New-Object System.Net.HttpListener
try{
Write-Verbose "Registering prefix $UriPrefix"
$Listener.Prefixes.Add($UriPrefix)
}
catch{
Write-Error -Exception $_.Exception -Message "UriPrefix $UriPrefix could not be registered"
return $null
}
Write-Verbose "Prefix registered, starting listener"
$Listener.Start()
# Wait for a connection
$Context = $Listener.GetContext()
$Request = $Context.Request
$Response = $Context.Response
}
process{
$Body += $ResponseData
}
end{
Write-Verbose "$($Request.Headers.Count) Request Headers:"
$Request.Headers.AllKeys |% {
Write-Verbose "$_`: $($Request.Headers[$_])"
}
$RequestStrings = @()
# If there is no input - don't bother with it
if($Request.InputStream.Length -gt 0)
{
Write-Verbose ""
$InStream = $Request.InputStream
$Reader = New-Object System.IO.StreamReader -ArgumentList $InStream
do
{
$RequestStrings += $Reader.ReadLine()
} while (-not $Reader.EndOfStream)
Write-Verbose "Request Body"
Write-Verbose $RequestStrings
}
else
{
Write-Verbose "No Request Body"
}
# Prepare and encode our response body
$ResponseBody = $Body -join "`n"
$ResponseBuffer = $Encoding.GetBytes($ResponseBody)
Write-Verbose "Content-Length: $($ResponseBuffer.Length)"
$Response.ContentLength64 = $ResponseBuffer.Length
$OutStream = $Response.OutputStream
try{
# Start writing the Response back
Write-Verbose "Writing Response buffer to output stream"
$OutStream.Write($ResponseBuffer,0,$ResponseBuffer.Length)
}
catch{
Write-Error $_
}
finally{
Write-Verbose "Cleaning up"
$OutStream.Close()
$Listener.Stop()
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment