Private/Test/Test-IsDomainComputer.ps1
|
function Test-IsDomainComputer { <# .SYNOPSIS Tests if the current computer is joined to an Active Directory domain. .DESCRIPTION Checks if the computer is a member of an Active Directory domain by querying the Win32_ComputerSystem WMI class PartOfDomain property. This is the most reliable method to determine domain membership status. This works regardless of the current user's authentication context and does not require network connectivity to the domain. This is useful for determining whether domain-based operations are possible when auditing Active Directory Certificate Services. .INPUTS None. This function does not accept pipeline input. .OUTPUTS System.Boolean Returns $true if the computer is joined to an Active Directory domain. Returns $false if the computer is in a workgroup, Azure AD joined, or standalone. .EXAMPLE Test-IsDomainComputer Returns $true if the computer is domain-joined. .EXAMPLE if (Test-IsDomainComputer) { Write-Host "Computer is domain-joined" } else { Write-Host "Computer is not domain-joined (workgroup or standalone)" } Conditionally executes code based on domain membership. .EXAMPLE if (-not (Test-IsDomainComputer)) { throw "This operation requires a domain-joined computer" } Throws an error if the computer is not domain-joined. .NOTES This function queries the Win32_ComputerSystem WMI/CIM class, which is the most reliable method for checking domain membership. It works even when: - Running as a local administrator - Domain controllers are unreachable - Using a local account on a domain-joined machine Does not work for Azure AD/Entra ID joined devices (returns $false). .LINK https://learn.microsoft.com/en-us/windows/win32/cimwin32prov/win32-computersystem #> [CmdletBinding()] [OutputType([bool])] param ( ) #requires -Version 5.1 try { Write-Verbose "Querying Win32_ComputerSystem to check domain membership" $computerSystem = Get-CimInstance -ClassName Win32_ComputerSystem -ErrorAction Stop $isDomainJoined = [bool]$computerSystem.PartOfDomain Write-Verbose "Computer: $($computerSystem.Name), Domain: $($computerSystem.Domain), PartOfDomain: $isDomainJoined" $isDomainJoined } catch { $errorRecord = [System.Management.Automation.ErrorRecord]::new( $_.Exception, 'ComputerSystemQueryFailed', [System.Management.Automation.ErrorCategory]::NotSpecified, $null ) $PSCmdlet.WriteError($errorRecord) return $false } } |