首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >为什么powershell http服务器代码不能工作

为什么powershell http服务器代码不能工作
EN

Stack Overflow用户
提问于 2020-12-19 08:10:13
回答 1查看 82关注 0票数 0

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

当浏览到http://localhost:8080/index.html时,我得到一个错误: Oops,页面不可用!代码有问题吗?我看不到什么?

代码语言:javascript
复制
    # 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()
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-12-19 08:26:21

如果你只转到http://localhost:8080/,你也必须有一个index.html列表才能浏览到。

只需修改$htmlContents部分,如下所示:

代码语言:javascript
复制
# 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>'
}

您也可以使用这样的语句。

代码语言:javascript
复制
$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"
}

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/65365457

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档