I found a couple of ways to gather the domain name information from T-SQL, again for the most part its using xp_cmdshell to run either a command or a PowerShell command. Ive left the PoSh and CMD methods as its still a useful note for if your writing a PowerShell script etc.

 

/*
Return Windows OS DOMAIN 
*/

-- TSQL
SELECT default_domain() AS 'Domain'

-- Undocumented SP
EXEC Master.dbo.xp_LoginConfig 'Default Domain'

-- Return Domain of Instance with xp_cmdshell
CREATE TABLE #xp_cmdshellOutPut
    (
      OutPut NVARCHAR(2000)
    );

DECLARE @cmd NVARCHAR(2000);
SET @cmd = 'echo %userdomain%';

INSERT  INTO #xp_cmdshellOutPut
        ( OutPut )
        EXEC xp_cmdshell @cmd;

DELETE  FROM #xp_cmdshellOutPut
WHERE   OutPut IS NULL  

SELECT  OutPut 
FROM    #xp_cmdshellOutPut

DROP TABLE #xp_cmdshellOutPut;


-- Return Domain of Instance with PowerShell (WMI)
CREATE TABLE #xp_cmdshellOutPut
    (
      OutPut NVARCHAR(2000)
    );

DECLARE @cmd NVARCHAR(2000);
SET @cmd = 'powershell.exe (gwmi WIN32_ComputerSystem).Domain';

INSERT  INTO #xp_cmdshellOutPut
        ( OutPut )
        EXEC xp_cmdshell @cmd;

DELETE  FROM #xp_cmdshellOutPut
WHERE   OutPut IS NULL  

SELECT  OutPut 
FROM    #xp_cmdshellOutPut

DROP TABLE #xp_cmdshellOutPut;
Advertisements