Powershell http server

From WikiWiki
Jump to navigation Jump to search

https://www.msxfaq.de/code/powershell/pshttpserver.htm


$listener = New-Object System.Net.HttpListener $listener.Prefixes.Add('http://+:81/') # Must GENAU mit der Angabe in NETSH übereinstimmen $listener.Start()

$basename = (get-date -Format yyyyMMddHHmmss) $count = 0

$Host.UI.RawUI.FlushInputBuffer() [console]::TreatControlCAsInput = $true write-host "Press any key to end after the next incoming request" while (!([console]::KeyAvailable)) {

  $count++
  write-host ("Listening on " + $listener.Prefixes )
  $context = $listener.GetContext() # Warte auf eingehende Anfragen
  write-host "------- New Request ($count) arrived ------------"
  $request = $context.Request
  write-host (" URL.AbsoluteUri:" + $request.URL.AbsoluteUri)
  write-host (" HttpMethod     :" + $request.HttpMethod)
  if ($request.HasEntityBody) {
     write-host "Exporting Body"
     # converting streamreader to string
     [byte[]]$buffer = new-object byte[] 4096
     $encoding = [System.Text.Encoding]::GetEncoding($null)
     [int]$count = 0
     [string]$rcvStream =""
     do {
        $count = $request.InputStream.Read($buffer, 0, $buffer.Length)
        $rcvStream += $encoding.GetString($buffer, 0, $count)
     } while ($count -gt 0)		
     $rcvStream | out-file -filepath ("request"+$basename+$count+".txt")
  }
  else {
     write-host "No Body"
  }
  write-host "------- Sending OK Response ------------"
  $response = $context.Response
  $response.ContentType = 'text/plain'
  $message = "Anfrage verarbeitet"
  [byte[]] $buffer = [System.Text.Encoding]::UTF8.GetBytes($message)
  $response.ContentLength64 = $buffer.length
  $response.OutputStream.Write($buffer, 0, $buffer.length)
  $response.OutputStream.close()

} $listener.Stop()