3
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

PowerShellで書いたWebサーバを他のPCからもアクセス許可する

Last updated at Posted at 2016-03-03

参考

設定

  • コマンドプロンプトを管理者権限で実行し以下
8080portでListenすることを許可
netsh http add urlacl url=http://*:18080/ user=everyone
  • 追加:netsh http add
  • 削除:netsh http delete
  • 一覧:netsh http show urlacl

Webサーバ起動

httpListener.ps1
  param($Port=18080, $HomePage='mdwiki.html', $DefaultPage=$HomePage)
- $urlRoot = "http://localhost:$Port/"
- $urlMain = $urlRoot+$HomePage
+ $urlRoot = "http://+:$Port/"
+ $urlMain = "http://localhost/"+$HomePage
  $parentPath = [IO.Path]::GetDirectoryName($MyInvocation.InvocationName)
  
  $listener = New-Object Net.HttpListener
  $listener.Prefixes.add($urlRoot)
  
  try{
-     "localhostで簡易httpサーバーを作動させます。"|oh
+     $urlRoot+"で簡易httpサーバーを作動させます。"|oh
      try {
          $listener.Start()
      } finally {
          #起動ついでにブラウザで開いてやる
          #Start()に失敗するケースでも既にHttpサーバーが動いているケースを期待してURLは開く
          "$urlMain を開きます。"|oh
          start $urlMain
      }
  
      $running = $true
      while($running){
          $context = $listener.GetContext()
          $request = $context.Request
          $response = $context.Response
  
          ($url = $request.RawUrl)|oh
          $path = $url.TrimStart('/').split("?")[0]
          if(!$path) {
              "def:"+$DefaultPage|oh
              $path = $DefaultPage
          }
  
          $fullPath = [IO.Path]::Combine($parentPath, $path)
          $content = [byte[]]@()
          if( [IO.File]::Exists($fullPath) ){
              $content = [IO.File]::ReadAllBytes($fullPath)
          } else {
              $response.StatusCode = 404
          }
  
          $response.OutputStream.Write($content, 0, $content.Length)
          $response.Close()
      }
  } finally {
      #スクリプトではあまり真面目にリソース管理しようとは思わないけれども一応
      $listener.Dispose()
  }
  '終了します。'|oh
  pause
起動
powershell -ExecutionPolicy RemoteSigned -File httpListener.ps1
3
6
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?