-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathPowershell-WebServer.ps1
More file actions
67 lines (60 loc) · 1.87 KB
/
Powershell-WebServer.ps1
File metadata and controls
67 lines (60 loc) · 1.87 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
[cmdletBinding(SupportsShouldProcess=$false,ConfirmImpact='Low')]
param(
#Listening Endpoint
[Parameter(Mandatory=$false,ValueFromPipeline=$false)] $HTTPEndPoint = 'http://localhost:8080/'
,
# LocalPath
[Parameter(Mandatory=$true,ValueFromPipeline=$false)] $LocalRoot = 'c:\wwwroot\'
)
$ErrorActionPreference = 'Stop'
$VerbosePreference = 'Continue'
function Get-HTTPResponse {
param(
[Parameter(Mandatory=$false,ValueFromPipeline=$false)] $Response,
[Parameter(Mandatory=$false,ValueFromPipeline=$false)] $Path
)
try {
Write-Verbose "Determine MimeType of $path ..."
$mimetype = [System.Web.MimeMapping]::GetMimeMapping($path)
Write-Verbose " - $mimetype"
# Generate Response
$content = ( Get-Content -Path $path -Raw )
$buffer = [System.Text.Encoding]::UTF8.GetBytes($content)
$response.ContentLength64 = $buffer.Length
$response.OutputStream.Write($buffer, 0, $buffer.Length)
}
catch [System.Exception] {
Write-Verbose "ERROR: $($_)"
return ""
}
}
$listener = New-Object System.Net.HttpListener
$listener.Prefixes.Add( $HTTPEndPoint )
$listener.Start()
Write-Verbose "Listening at $HTTPEndPoint..."
while ($listener.IsListening) {
$context = $listener.GetContext()
$requestUrl = $context.Request.Url
$response = $context.Response
try {
$localPath = $requestUrl.LocalPath
#Close server
if ($localPath -eq '/kill') {
Write-Verbose "Killing ...";
$response.StatusCode = 200;
$response.Close();
$listener.Close();
break;
}
$FullPath = join-path -Path $LocalRoot -ChildPath $LocalPath
if ( Test-Path $FullPath ) {
Write-Verbose "Querying $requestUrl ..."
Get-HTTPResponse -Response $response -Path $FullPath
} else {
$response.StatusCode = 404
}
} catch {
$response.StatusCode = 500
}
$response.Close()
}