Code Scrap: Testing for Domain presence on Windows

I’ve been making a support utility that monitors if message queues and database tables are being read from and written to as part of the day to day activities in the business I work in. The support utility is a C# WinForms application that I have running whenever I’m working.

What with Covid going on and working from home more, I’m now connecting to the office via VPN. My support utility goes absolutely MENTAL throwing errors whenever it’s running and I’m not connected to the VPN, as it can’t communicate with the business servers. I’ve got the errors being captured in error handling logic, but I still get a pop up saying the server can’t be reached.

What would be better in this scenario, would be if the Support Utility could detect that it wasn’t connected to the corporate network, and thus not even attempt to try and talk to the server, for the times I was not on the VPN.

So – here’s a simple snippet of code, that will check for your corporate domain and return TRUE if your domain is found, FALSE otherwise.

public bool CheckDomainPresence()
{
bool onNetwork = false;
try
{
var domain = System.DirectoryServices.ActiveDirectory.Domain.GetComputerDomain();
if (domain.Name.Contains(“mybusiness.com”)) // This is entirely optional, and useful to ensure that the domain name returned contains your corporate domain
{
onNetwork = true;
}
else
{
Console.WriteLine($”Domain {domain.Name} does not match expected Europa Domain value.”);
}
}
catch (Exception ex)
{
Console.WriteLine($”Could not find domain. {ex.Message}”);
}
return onNetwork;
}

The above block will always return TRUE when the program can talk to the corporate domain.

You can implement this in any .NET language, including PowerShell.

Here’s an equivalent in PowerShell:

try
{
$i = [System.DirectoryServices.ActiveDirectory.Domain]::GetComputerDomain()
Write-Host $i
if ($i -like ‘mybusiness.com‘) {
Write-Host ‘Connected to the corporate domain’
}
else {
Write-Host ‘This is not the corporate domain’
}
}
catch
{
Write-Host ‘Not on the domain’
}

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.