【问题标题】:why this powershell http server code doesn't work为什么这个 powershell http 服务器代码不起作用
【发布时间】:2021-03-29 14:30:39
【问题描述】:

我将此代码 https://community.idera.com/database-tools/powershell/powertips/b/tips/posts/creating-powershell-web-server 复制并粘贴到包含 index.html 文件的 powershell 控制台目录中

浏览到 http://localhost:8080/index.html 时出现错误 糟糕,页面不可用! 看不到代码是不是有什么问题?

    # enter this URL to reach PowerShell’s web server
$url = 'http://localhost:8080/'

# HTML content for some URLs entered by the user
$htmlcontents = @{
  'GET /'  =  '<html><building>Here is PowerShell</building></html>'
  'GET /services'  =  Get-Service | ConvertTo-Html

}

# start web server
$listener = New-Object System.Net.HttpListener
$listener.Prefixes.Add($url)
$listener.Start()

try
{
  while ($listener.IsListening) {  
    # process received request
    $context = $listener.GetContext()
    $Request = $context.Request
    $Response = $context.Response

    $received = '{0} {1}' -f $Request.httpmethod, $Request.url.localpath
    
    # is there HTML content for this URL?
    $html = $htmlcontents[$received]
    if ($html -eq $null) {
      $Response.statuscode = 404
      $html = 'Oops, the page is not available!'
    } 
    
    # return the HTML to the caller
    $buffer = [Text.Encoding]::UTF8.GetBytes($html)
    $Response.ContentLength64 = $buffer.length
    $Response.OutputStream.Write($buffer, 0, $buffer.length)
    
    $Response.Close()
  }
}
finally
{
  $listener.Stop()
}

【问题讨论】:

    标签: powershell


    【解决方案1】:

    如果您只访问http://localhost:8080/,它确实有效,您还必须有一个 index.html 列表才能浏览到它。

    只需像这样修改$htmlContents 部分:

    # HTML content for some URLs entered by the user
    $htmlcontents = @{
      'GET /'  =  '<html><building>Here is PowerShell</building></html>'
      'GET /services'  =  Get-Service | ConvertTo-Html
      'GET /index.html'  =  '<html><building>this is my index page</building></html>'
    }
    
    

    你也可以有这样的声明。

    $htmlcontents = @{
      'GET /'  =  '<html><building>Here is PowerShell</building></html>'
      'GET /services'  =  Get-Service | ConvertTo-Html
      'GET /index.html'  =  '<html><building>this is my index page</building></html>'
      'GET /fromPage.html' = Get-content "C:\temp\fence.txt"
    }
    

    【讨论】:

      猜你喜欢
      • 2021-07-30
      • 1970-01-01
      • 2018-11-05
      • 2012-02-22
      • 2023-03-03
      • 2017-10-02
      • 2016-07-10
      • 2010-12-14
      • 2017-04-09
      相关资源
      最近更新 更多