powershell:webserver
PowerShellを使った簡易的なWebサーバー
# ルートディレクトリを指定(この中のファイルを配信) $RootDir = "\Path\TO\wwwroot" # HttpListenerを初期化 $listener = New-Object System.Net.HttpListener $listener.Prefixes.Add("http://localhost:8080/") # 8080で待ち受け $listener.Start() Write-Host "Serving files from $RootDir at http://localhost:8080/" # MIMEタイプの辞書(最低限) $mimeTypes = @{ ".html" = "text/html" ".htm" = "text/html" ".css" = "text/css" ".js" = "application/javascript" ".png" = "image/png" ".jpg" = "image/jpeg" ".jpeg" = "image/jpeg" ".gif" = "image/gif" ".ico" = "image/x-icon" } while ($listener.IsListening) { $context = $listener.GetContext() $request = $context.Request $response = $context.Response # リクエストされたパスを取得 $path = $request.Url.LocalPath.TrimStart("/") if ([string]::IsNullOrEmpty($path)) { $path = "index.html" } # デフォルト index.html $filePath = Join-Path $RootDir $path if (Test-Path $filePath) { try { $bytes = [System.IO.File]::ReadAllBytes($filePath) # MIMEタイプを判定 $ext = [System.IO.Path]::GetExtension($filePath).ToLower() if ($mimeTypes.ContainsKey($ext)) { $response.ContentType = $mimeTypes[$ext] } else { $response.ContentType = "application/octet-stream" } $response.ContentLength64 = $bytes.Length $response.OutputStream.Write($bytes, 0, $bytes.Length) } catch { $response.StatusCode = 500 $msg = "500 Internal Server Error" $bytes = [System.Text.Encoding]::UTF8.GetBytes($msg) $response.OutputStream.Write($bytes, 0, $bytes.Length) } } else { $response.StatusCode = 404 $msg = "404 Not Found" $bytes = [System.Text.Encoding]::UTF8.GetBytes($msg) $response.OutputStream.Write($bytes, 0, $bytes.Length) } $response.OutputStream.Close() }
powershell/webserver.txt · 最終更新: 2025/08/27 23:26 by mikoto