在不同的操作系统中运行powershell脚本

问题描述 投票:0回答:1

我试图在Server 2012中运行下面提到的命令,它从管理员用户组中提取用户。但是在Server 2008R2中,它正在从整个域中拉出来

Get-WmiObject -Class Win32_GroupUser `
| where{$_.GroupComponent -like "*Administrators*"} `
|foreach { 
$data = $_.PartComponent -split "\," 
$data[1].Remove(0,5).Replace('"','') 
} 
powershell powershell-v2.0 admin active-directory-group
1个回答
0
投票

正如您所猜测的那样,问题是win2008R2只有PS 2.0.x.我认为这个命令where{$_.GroupComponent -like "*Administrators*"}在该版本中不可用,因此它将整个AD查询为后备(这是猜测)。

根据您的描述,我不明白您是否要查询本地服务器或域,因此我将同时输入两者(所有功能都在win2008R2(PS版本2.0.50727)上):

查询本地管理员和

#get servers by AD OU
If (!(Get-Module ActiveDirectory)) {
    Import-Module ActiveDirectory
}
function get-localadmins{
  [cmdletbinding()]
  Param(
  [string]$server
  )
  $group = get-wmiobject win32_group -ComputerName $server -Filter "LocalAccount=True AND SID='S-1-5-32-544'"
  $query = "GroupComponent = `"Win32_Group.Domain='$($group.domain)'`,Name='$($group.name)'`""
  $list = Get-WmiObject win32_groupuser -ComputerName $server -Filter $query
  $list | %{$_.PartComponent} | % {$_.substring($_.lastindexof("Domain=") + 7).replace("`",Name=`"","\")}
}

get-localadmins 'your_server_name'

如果您的目标是查询整个AD,那么您可以使用:

在Windows 2008 R2 SP1上,它可能会产生错误:System.DirectoryServices.AccountManagement.PrincipalOperationException:枚举组时发生错误(1301)。该组的SID无法解决。

您必须安装Microsoft的修补程序:https://support.microsoft.com/en-us/help/2830145/sid-s-1-18-1-and-sid-s-1-18-2-cannot-be-mapped-on-windows-based-computers-in-a-domain-environment?wa=wsignin1.0%3Fwa%3Dwsignin1.0

下面的代码来自这里:https://stackoverflow.com/a/8057025/6059896(所有作者的信用) - 只改变了变量的名称,以图我的编码风格。

$Recurse = $true

Add-Type -AssemblyName System.DirectoryServices.AccountManagement
$context_type = [System.DirectoryServices.AccountManagement.ContextType]::Domain
$group_principal_identity=[System.DirectoryServices.AccountManagement.GroupPrincipal]::FindByIdentity($ct,'Administrators')
$group.GetMembers($Recurse)
© www.soinside.com 2019 - 2024. All rights reserved.