PowerShell判断Windows系统是Server还是Client 3


在测试中可能会碰到须要判断当前或者远程系统是Windows Server还是Windows Client,以区别处理。我更倾向于Windows 中的[environment]::OSVersion中包含了这一属性,可惜啦,没有。
还有一种,是根据[environment]::OSVersion.Version建立一个系统与版本的词典。

另外在网上遇到了两种方法,改成了PowerShell版本的。

  • 一种是调用shlwapi.dll中的方法:
$signature=@"
public class OSType
{
    public static bool IsWindowsServer()
    {
        return OSType.IsOS (OSType.OS_ANYSERVER);
    }
    const int OS_ANYSERVER =   9;
    [System.Runtime.InteropServices.DllImport("shlwapi.dll", SetLastError=true, EntryPoint="#437")]
    private static extern bool IsOS(int os);
}
"@
Add-Type -TypeDefinition $signature
[OSType]::IsWindowsServer()
  • 另外一种是通过WMI对象的Win32_OperatingSystem类:

官方说属性为ProductType返回1为Client,返回3为Server

function Is-WindowsServer
{
param($ComputerName="Localhost")
$ops = Get-WmiObject -ComputerName $ComputerName  -Class Win32_OperatingSystem
return $ops.ProductType -eq 3
}

推荐使用第二种,可以获取远程机器是server或者client的信息,如果需要还可以照猫画虎加入用户凭据参数,因为get-wmiobject支持参数–Credential

如果遇到其它方法,恳请大哥留言推荐!

本文链接: https://www.pstips.net/determine-windows-system-is-server-or-client.html
请尊重原作者和编辑的辛勤劳动,欢迎转载,并注明出处!

关于 Mooser Lee

我是一个Powershell的爱好者,创建了PowerShell中文博客,热衷于Powershell技术的搜集和分享。本站部分内容来源于互联网,不足之处敬请谅解,并欢迎您批评指正。

回复 Mooser Lee 取消回复

您的电子邮箱地址不会被公开。 必填项已用*标注

3 条评论 “PowerShell判断Windows系统是Server还是Client

  • codecook

    Get-WmiObject -ComputerName 10.0.11.125 -Class Win32_OperatingSystem
    Get-WmiObject : 拒绝访问。 (异常来自 HRESULT:0x80070005 (E_ACCESSDENIED))
    请问远程执行这个命令的条件是什么??谢谢

    • Mooser Lee 文章作者

      这个我真没试过,我一般是这样:
      如果当前机器的当前账号可以登录远程机器,应当是可以访问的。否则,需要显示指定credentials(用户凭据)。
      另外如果跨域,域之间是不是可信任的。
      基本上可以确定是你没有指定远程机器的用户名和密码:
      比如: 当我访问

      
      PS C:\> Get-WmiObject -computername 10.225.62.120 -Class Win32_OperatingSystem
      Get-WmiObject : Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED))
      At line:1 char:1
      + Get-WmiObject -computername 10.225.62.120 -Class Win32_OperatingSystem
      + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
          + CategoryInfo          : NotSpecified: (:) [Get-WmiObject], UnauthorizedAccessException
          + FullyQualifiedErrorId : System.UnauthorizedAccessException,Microsoft.PowerShell.Commands.GetWmiObjectCommand
      

      但是当我指定用户名和密码后:

      PS C:\> Get-WmiObject -computername 10.225.62.120 -Class Win32_OperatingSystem -Credential (Get-Credential)
      
      cmdlet Get-Credential at command pipeline position 1
      Supply values for the following parameters:
      Credential
      
      
      SystemDirectory : C:\Windows\system32
      Organization    : Microsoft Corporation
      BuildNumber     : 9600
      RegisteredUser  : SCOM Team
      SerialNumber    : 00252-80000-01997-AA325
      Version         : 6.3.9600