web1536/powershell_test
0
1# servidor_api2.ps12# Servidor Web API simples PowerShell + C# (compatível PS 5.1 e 7+)3 4param (5 [int]$PORT = 80806)7 8# Detecta se é Windows ou Linux9#$isWindows = $PSVersionTable.OS -match "Windows"10 11# Define prefix conforme sistema12#$prefix = if ($isWindows) { "http://localhost:$PORT/" } else { "http://*:$PORT/" }13$prefix = "http://*:$PORT/"14 15# Código C# do servidor16$code = @"17using System;18using System.Net;19using System.Text;20using System.IO;21 22public class SimpleApiServer {23 private string _prefix;24 public SimpleApiServer(string prefix) {25 _prefix = prefix;26 }27 28 public void Start() {29 HttpListener listener = new HttpListener();30 listener.Prefixes.Add(_prefix);31 listener.Start();32 Console.WriteLine("Servidor iniciado na URL " + _prefix);33 34 while (true) {35 var context = listener.GetContext();36 var request = context.Request;37 var response = context.Response;38 string body = "";39 40 try {41 string path = request.Url.AbsolutePath.ToLower();42 43 if (path == "/") {44 body = "{\"msg\": \"API PowerShell + C# ativa!\"}";45 }46 else if (path.StartsWith("/hello")) {47 string name = request.QueryString["name"];48 if (string.IsNullOrEmpty(name)) name = "Mundo";49 string msg = "Olá, " + name;50 body = "{\"msg\": \"" + msg + "\"}";51 }52 else if (path == "/hora") {53 string hora = DateTime.Now.ToString("HH:mm:ss");54 body = "{\"hora\": \"" + hora + "\"}";55 }56 else {57 body = "{\"erro\": \"Rota nao encontrada\"}";58 response.StatusCode = 404;59 }60 }61 catch (Exception ex) {62 body = "{\"erro\": \"" + ex.Message + "\"}";63 response.StatusCode = 500;64 }65 66 response.ContentType = "application/json; charset=utf-8";67 68 using (var writer = new StreamWriter(response.OutputStream, Encoding.UTF8)) {69 writer.Write(body);70 }71 }72 }73}74"@75 76# Adiciona o tipo C# ao PowerShell77Add-Type -TypeDefinition $code -Language CSharp78 79# Cria e inicia o servidor80$server = [SimpleApiServer]::new($prefix)81$server.Start()82 