Monthly Archives: October 2018

A simpel rest web service with powershell

Below a sample webservice for exposte active directory queries using a powershell server… Ttest it wirh http://localhost:8000/user/<domainname>/<SamAccountName>

# Create a listener on port 8000
$listener = New-Object System.Net.HttpListener
$listener.Prefixes.Add(‘http://+:8000/’)
$listener.Start()
‘Listening …’

# Run until you send a GET request to /end
while ($true) {
$context = $listener.GetContext()

# Capture the details about the request
$request = $context.Request

# Setup a place to deliver a response
$response = $context.Response

# Break from loop if GET request sent to /end
if ($request.Url -match ‘/end$’) {
break
} else {

# Split request URL to get command and options
$requestvars = ([String]$request.Url).split(“/”);

# If a request is sent to http:// :8000/user/<domainname>/<SamAccountName>

if ($requestvars[3] -eq “user”) {
$dom = $requestvars[4]
$user = $requestvars[5]
$domainname = $dom + “.redaelli.org”
$dc = Get-ADDomainController -DomainName $domainname -Discover -NextClosestSite
echo $dc
$searchbase = ‘DC=’ + $dom + ‘,DC=redaelli,DC=org’
# Get the class name and server name from the URL and run get-WMIObject
$result = Get-ADUser -Server $dc.HostName[0] -SearchBase $searchbase -Filter {SamAccountName -eq $user} -Properties * | select SamAccountName, sn,GivenName,DisplayName,mail,DistinguishedName,telephoneNumber,mobile,l,company,co,whenCreated,whenChanged,PasswordExpired,PasswordLastSet,PasswordNeverExpires,lockedOut,LastLogonDate,lockoutTime

# Convert the returned data to JSON and set the HTTP content type to JSON
$message = $result | ConvertTo-Json;
$response.ContentType = ‘application/json’;

} else {

# If no matching subdirectory/route is found generate a 404 message
$message = “This is not the page you’re looking for.”;
$response.ContentType = ‘text/html’ ;
}

# Convert the data to UTF8 bytes
[byte[]]$buffer = [System.Text.Encoding]::UTF8.GetBytes($message)

# Set length of response
$response.ContentLength64 = $buffer.length

# Write response out and close
$output = $response.OutputStream
$output.Write($buffer, 0, $buffer.length)
$output.Close()
}
}

#Terminate the listener
$listener.Stop()