Power Shell创建简易Web Server

start-job { 
    $p="c:\temp\"
    # $p = Get-Location 可以获取当前用户的目录,如果这样使用后面的$p改为$p.path
    $H=New-Object Net.HttpListener
    $H.Prefixes.Add("http://+:89/")
    $H.Start()
    While ($H.IsListening) {
        $HC=$H.GetContext()
        $HR=$HC.Response
        $HR.Headers.Add("Content-Type","text/plain")

        <#
        $file=Join-Path $p ($HC.Request).RawUrl
        $text=[IO.File]::ReadAllText($file)
        $text=[Text.Encoding]::UTF8.GetBytes($text)
        
        $HR.ContentLength64 = $text.Length
        $HR.OutputStream.Write($text,0,$text.Length)
        #>
        
           
        switch(($HC.Request).RawUrl){
            "/hello" {$text="hell wolrd"}
            "/time" {$text=[DateTime]::Now.ToShortDateString()}

        }
        $text=[Text.Encoding]::UTF8.GetBytes($text)
        
        $HR.ContentLength64 = $text.Length
        $HR.OutputStream.Write($text,0,$text.Length)

        $HR.Close()
    }
    $H.Stop()
}

  

posted @ 2022-05-09 16:43  Ender.Lu  阅读(156)  评论(0编辑  收藏  举报