Determining if the program is running on Windows Server

前端 未结 5 370
北恋
北恋 2020-12-03 04:06

I would like to determine if my program is running on a version of Windows Server. Apparently, System.Environment does not contain information about the fact th

5条回答
  •  醉梦人生
    2020-12-03 04:18

    I had the same issue, albeit in scripting.

    I have found this value; I am querying it using WMI:

    https://msdn.microsoft.com/en-us/library/aa394239(v=vs.85).aspx
    Win32_OperatingSystem
    ProductType
        Data type: uint32
        Access type: Read-only
        Additional system information.
        Work Station (1)
        Domain Controller (2)
        Server (3)
    

    I tested this for the following operating system versions:

    • Windows XP Professional SP3
    • Windows 7 Enterprise
    • Windows 8.1 Pro
    • Windows 8.1 Enterprise
    • Windows 10 Pro 10.0.16299
    • Windows Server 2003 R2 Standard Edition
    • Windows Server 2003 R2 Standard Edition x64
    • Windows Server 2008 R2 Standard
    • Windows Server 2012 Datacenter
    • Windows Server 2012 R2 Datacenter

    Find my example batch file below.

    Lucas.

    for /f "tokens=2 delims==" %%a in ( 'wmic.exe os get producttype /value' ) do (
        set PRODUCT_TYPE=%%a
    )
    if %PRODUCT_TYPE%==1 set PRODUCT_TYPE=Workstation
    if %PRODUCT_TYPE%==2 set PRODUCT_TYPE=DomainController
    if %PRODUCT_TYPE%==3 set PRODUCT_TYPE=Server
    echo %COMPUTERNAME%: %PRODUCT_TYPE%
    

    You can easily do this in C#:

    using Microsoft.Management.Infrastructure;
    ...
    string Namespace = @"root\cimv2";
    string className = "Win32_OperatingSystem";
    
    CimInstance operatingSystem = new CimInstance(className, Namespace);
    

提交回复
热议问题