param ( [Parameter(Mandatory = $true)] [string]$Path, [Parameter(Mandatory = $false)] [int]$Port = 8080 ) Add-Type -AssemblyName System.Net.HttpListener if (-Not (Test-Path $Path)) { Write-Error "โŒ Der angegebene Pfad '$Path' existiert nicht." exit 1 } $Directory = if (Test-Path $Path -PathType Leaf) { Split-Path $Path } else { $Path } $FileName = if (Test-Path $Path -PathType Leaf) { Split-Path $Path -Leaf } else { $null } $listener = New-Object System.Net.HttpListener $listener.Prefixes.Add("http://+:$Port/") $listener.Start() Write-Host "๐ŸŒ HTTP-Server lรคuft auf Port $Port" Write-Host "๐Ÿ“‚ Freigegeben: $Path" Write-Host "๐Ÿ“ก Warte auf Anfragen... (Strg+C zum Beenden)" # Event-Handler fรผr sauberes Beenden $onExit = { Write-Host "`n๐Ÿ›‘ Server wird beendet..." $listener.Stop() $listener.Close() Write-Host "โœ… Server wurde gestoppt." exit } Register-EngineEvent PowerShell.Exiting -Action $onExit | Out-Null while ($listener.IsListening) { try { $context = $listener.GetContext() $request = $context.Request $response = $context.Response $clientIP = $request.RemoteEndPoint.Address.ToString() $urlPath = $request.Url.AbsolutePath.TrimStart('/') $localPath = Join-Path $Directory $urlPath if ($request.Url.AbsolutePath -eq "/") { # Indexseite generieren $items = Get-ChildItem -Path $Directory $html = "

Index von $Directory

" $bytes = [System.Text.Encoding]::UTF8.GetBytes($html) $response.ContentType = "text/html" } elseif ($FileName -and ($urlPath -ne $FileName)) { $response.StatusCode = 403 $bytes = [System.Text.Encoding]::UTF8.GetBytes("403 - Zugriff verweigert") } elseif (Test-Path $localPath -PathType Leaf) { Write-host "Reading $($localPath)" $bytes = [System.IO.File]::ReadAllBytes($localPath) $response.ContentType = "application/octet-stream" } else { $response.StatusCode = 404 $bytes = [System.Text.Encoding]::UTF8.GetBytes("404 - Datei nicht gefunden") } $response.ContentLength64 = $bytes.Length $response.OutputStream.Write($bytes, 0, $bytes.Length) $response.Close() $timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss" Write-Host "[$timestamp] $clientIP โ†’ /$urlPath ($($bytes.Length) Bytes)" } catch { Write-Warning "โš ๏ธ Fehler: $_" } }