How to detect if machine is joined to domain?
You can PInvoke to Win32 API's such as NetGetDcName which will return a null/empty string for a non domain-joined machine.
Even better is NetGetJoinInformation which will tell you explicitly if a machine is unjoined, in a workgroup or in a domain.
Using NetGetJoinInformation
I put together this, which worked for me:
public class Test
{
public static bool IsInDomain()
{
Win32.NetJoinStatus status = Win32.NetJoinStatus.NetSetupUnknownStatus;
IntPtr pDomain = IntPtr.Zero;
int result = Win32.NetGetJoinInformation(null, out pDomain, out status);
if (pDomain != IntPtr.Zero)
{
Win32.NetApiBufferFree(pDomain);
}
if (result == Win32.ErrorSuccess)
{
return status == Win32.NetJoinStatus.NetSetupDomainName;
}
else
{
throw new Exception("Domain Info Get Failed", new Win32Exception());
}
}
}
internal class Win32
{
public const int ErrorSuccess = 0;
[DllImport("Netapi32.dll", CharSet=CharSet.Unicode, SetLastError=true)]
public static extern int NetGetJoinInformation(string server, out IntPtr domain, out NetJoinStatus status);
[DllImport("Netapi32.dll")]
public static extern int NetApiBufferFree(IntPtr Buffer);
public enum NetJoinStatus
{
NetSetupUnknownStatus = 0,
NetSetupUnjoined,
NetSetupWorkgroupName,
NetSetupDomainName
}
}
How to check if a device is AD joined or Azure AD joined/registered?
I need to check if my device is local Domain Joined or Azure AD joined/registered. How to check this?
You could get the answer from this document.
To verify whether a device is joined to an Azure AD, you can review the Access work or school dialog on your device.
Alternatively, you can run the following command: dsregcmd /status
On a successfully joined device, AzureAdJoined is Yes.
How to find if the local computer is in a domain?
Win32_ComputerSystem
has a PartOfDomain
property that indicates whether the computer is domain joined or not. There is also a workgroup property - that should be blank if the computer is on a domain.
Example:
if ((gwmi win32_computersystem).partofdomain -eq $true) {
write-host -fore green "I am domain joined!"
} else {
write-host -fore red "Ooops, workgroup!"
}
In PowerShell, how do I determine if a domain-joined computer is connected to the domain network?
This appears to work well, and should work on all versions of PowerShell:
function Test-DomainNetworkConnection
{
# Returns $true if the computer is attached to a network where it has a secure connection
# to a domain controller
#
# Returns $false otherwise
# Get operating system major and minor version
$strOSVersion = (Get-WmiObject -Query "Select Version from Win32_OperatingSystem").Version
$arrStrOSVersion = $strOSVersion.Split(".")
$intOSMajorVersion = [UInt16]$arrStrOSVersion[0]
if ($arrStrOSVersion.Length -ge 2)
{
$intOSMinorVersion = [UInt16]$arrStrOSVersion[1]
} `
else
{
$intOSMinorVersion = [UInt16]0
}
# Determine if attached to domain network
if (($intOSMajorVersion -gt 6) -or (($intOSMajorVersion -eq 6) -and ($intOSMinorVersion -gt 1)))
{
# Windows 8 / Windows Server 2012 or Newer
# First, get all Network Connection Profiles, and filter it down to only those that are domain networks
$domainNetworks = Get-NetConnectionProfile | Where-Object {$_.NetworkCategory -eq "Domain"}
} `
else
{
# Windows Vista, Windows Server 2008, Windows 7, or Windows Server 2008 R2
# (Untested on Windows XP / Windows Server 2003)
# Get-NetConnectionProfile is not available; need to access the Network List Manager COM object
# So, we use the Network List Manager COM object to get a list of all network connections
# Then we get the category of each network connection
# Categories: 0 = Public; 1 = Private; 2 = Domain; see: https://msdn.microsoft.com/en-us/library/windows/desktop/aa370800(v=vs.85).aspx
$domainNetworks = ([Activator]::CreateInstance([Type]::GetTypeFromCLSID([Guid]"{DCB00C01-570F-4A9B-8D69-199FDBA5723B}"))).GetNetworkConnections() | `
ForEach-Object {$_.GetNetwork().GetCategory()} | Where-Object {$_ -eq 2}
}
return ($domainNetworks -ne $null)
}
With this function defined, simply type:
Test-DomainNetworkConnection
If it returns $true, then you know you have connectivity to a domain controller.
how can I determine if the machine I am using is a domain controller
After much research... there are two ways:
Works on Windows 2008 server:
public bool isActiveDirectoryDomainServicesInstalled()
{
bool bRetval = false;
try
{
uint uID = 110;
string search = string.Format("SELECT * FROM Win32_ServerFeature WHERE ID = {0}", uID);
ManagementObjectSearcher oSearcher = new ManagementObjectSearcher("root\\CIMV2", search);
foreach (var oReturn in oSearcher.Get())
{
if ((uint)(oReturn["ID"]) == uID)
{
bRetval = true;
break;
}
}
}
catch (Exception)
{
bRetval = false;
}
return bRetval;
}
.
AND
.
Works on Windows 2008 and Windows 2012 servers
public bool IsThisMachineIsADomainController()
{
Domain domain = Domain.GetCurrentDomain();
string thisMachine = String.Format("{0}.{1}", Environment.MachineName, domain.ToString());
thisMachine = thisMachine.ToLower();
//Enumerate Domain Controllers
List<string> allDcs = new List<string>();
string name = "";
foreach (DomainController dc in domain.DomainControllers)
{
name = dc.Name.ToLower();
allDcs.Add(name);
}
return allDcs.Contains(thisMachine);
}
How to check if Join a computer to a domain was succeful
You could specify the parameter "-PassThru" for the command "Add-Computer". Based on your input the command would look like this:
$j = Add-Computer -DomainName mydomain -Credential mydomain\ -PassThru
"$j" now contains the information, if the join was successful. You can get the status with:
$j.HasSucceeded
It will give you "$True" on success and "$False" on error.
With that information you could form your IF-clause as you like:
IF ( $j.HasSucceeded -eq $false ) { ...
EDIT:
A simple example based on your input:
Do {
Try {
$j = Add-Computer -DomainName mydomain -Credential mydomain\test -PassThru -ErrorAction Stop
}
Catch {
$Error[0].Exception
}
} While ( $j.HasSucceeded -ne $true )
Kind regards
Related Topics
C# 4.0: How to Use a Timespan as an Optional Parameter with a Default Value
C# String Replace with Dictionary
Can Someone Explain How Bcrypt Verifies a Hash
Get Screen Resolution in Win10 Uwp App
Visual Studio 2010: How to Enforce Build Order of Projects in a Solution
Extract All Strings Between Two Strings
Client-Side Validation in Custom Validation Attribute - ASP.NET MVC 4
What Do the "+N" Values Mean at the End of a Method Name in a Stack Trace
Get Affected Rows on Executenonquery
How to Print PDF on Default Network Printer Using Ghostscript (Gswin32C.Exe) Shell Command
How to Create Trial Version of .Net Software
How to Format Timespan in Xaml
"The Linq Expression Node Type 'Invoke' Is Not Supported in Linq to Entities" - Stumped!
How to Get the Local Network Ip Address of a Computer Programmatically