我将此代码 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()
}
答案 0 :(得分:1)
如果您只访问 x
,它确实有效,您还必须有一个 index.html 列表才能浏览到该列表。
只需像这样修改 http://localhost:8080/
部分:
$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>'
}