Get join information with PowerShell – the hard way

Posted by

Why make it simple when you can make it the hard way?
– Because you can? 🙂

The reason for why I needed this is not relevant, but the options when you get information from your computer is. Quite often there are multiple ways to get information: Pure PowerShell commands, registry, environment variables, running cmd/3rd party commands, or Windows API/C# code.

To demonstrate I wrote alternative ways of getting the information of what domain or workgroup the computer is a member of, happy PowerShell coding


Get-ComputerInfo | fl CsDomain

Windows API/C# code wrapped in Powershell

Add-Type -TypeDefinition @"
namespace PInvoke {
    public enum NetJoinStatus
        NetSetupUnknownStatus = 0,

$NetGetJoinInformation = @'
[DllImport("Netapi32.dll", CharSet=CharSet.Unicode, SetLastError=true)]
public static extern int NetGetJoinInformation(
    string server, 
    out IntPtr domain,
    out int status);

$args1 = $null
$args2 = [IntPtr]::Zero
$args3 = New-Object PInvoke.NetJoinStatus;

$type = Add-Type -MemberDefinition $NetGetJoinInformation -Name NetJoin -Namespace Test -PassThru

$retValue = $type::NetGetJoinInformation($args1, [ref] $args2, [ref] $args3);

if ($retValue -eq 0) {
    Write-Host "Success"

    switch ($args3.ToString())
        $([PInvoke.NetJoinStatus]::NetSetupUnknownStatus.value__) { Write-Host ([PInvoke.NetJoinStatus]::NetSetupUnknownStatus); continue  }
        $([PInvoke.NetJoinStatus]::NetSetupUnjoined.value__) { Write-Host ([PInvoke.NetJoinStatus]::NetSetupUnjoined); continue }
        $([PInvoke.NetJoinStatus]::NetSetupDomainName.value__) { Write-Host "$([PInvoke.NetJoinStatus]::NetSetupDomainName): $([System.Runtime.InteropServices.Marshal]::PtrToStringAuto($args2))"; continue }
        $([PInvoke.NetJoinStatus]::NetSetupWorkgroupName.value__) { Write-Host "$([PInvoke.NetJoinStatus]::NetSetupWorkgroupName): $([System.Runtime.InteropServices.Marshal]::PtrToStringAuto($args2))"; continue }
        Default { write-host "Only errors" }

    Write-Host "Error: I did not include any error control here :)";

Leave a comment

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

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