Hello World
This sample spins up a small Kestrun server and returns plain text from a single route.
Prerequisites: see Introduction.
Full source
File: pwsh/tutorial/examples/1.1-Hello-World.ps1
<#
Sample Kestrun Server Configuration
This script demonstrates how to set up a simple Kestrun server with a single route.
The server will respond with "Hello, World!" when accessed.
FileName: 1.1-Hello-World.ps1
#>
param(
[int]$Port = 5000,
[IPAddress]$IPAddress = [IPAddress]::Loopback # Use 'Loopback' for safety in tests/examples
)
# Create a new Kestrun server
New-KrServer -Name 'Simple Server'
# Add a listener on port 5000 and IP address 127.0.0.1 (localhost)
Add-KrEndpoint -Port $Port -IPAddress $IPAddress
# Enable Kestrun configuration
Enable-KrConfiguration
# Map the route
Add-KrMapRoute -Verbs Get -Pattern '/hello' -ScriptBlock {
Write-KrTextResponse -InputObject 'Hello, World!' -StatusCode 200
# Or the shorter version
# Write-KrTextResponse "Hello, World!"
}
# Start the server asynchronously
Start-KrServer
Step-by-step
- Server: create the host with New-KrServer.
- Listener: bind to 127.0.0.1:5000 with Add-KrEndpoint.
- Configure: apply staged changes using Enable-KrConfiguration.
- Route: map
GET /hellovia Add-KrMapRoute with a script block handler. - Response: inside the route, call Write-KrTextResponse to return text/plain with status 200.
- Start: run the server with Start-KrServer and stop with Ctrl+C.
How it works
- Configuration is staged by cmdlets, then committed with Enable-KrConfiguration.
- Each route runs inside a request context (available as $Context) with Request/Response properties.
- Write-KrTextResponse is a convenience wrapper that sets Content‑Type to text/plain and writes the body.
- By default, a single listener is configured on 127.0.0.1:5000; you can add more listeners (e.g., HTTPS) later.
Try it
Save the sample locally so it’s easy to run. Copy the contents of pwsh/tutorial/examples/1.1-Hello-World.ps1 into a new file in an empty working folder (for example, hello-world.ps1), then run:
# From your working folder
pwsh .\hello-world.ps1
curl http://127.0.0.1:5000/hello
PowerShell alternative:
Invoke-WebRequest -Uri 'http://127.0.0.1:5000/hello' | Select-Object -ExpandProperty Content
Stop the server with Ctrl+C in the terminal where you ran the script.
References
- New-KrServer
- Add-KrEndpoint
- Enable-KrConfiguration
- Add-KrMapRoute
- Write-KrTextResponse
- Start-KrServer
Troubleshooting
- If the port is in use, choose a different port in Add‑KrListener.
Previous / Next
Previous: None Next: Route Options (MapRouteOptions)