在不同的操作系统中运行powershell脚本
问题描述:
我试图在服务器2012中运行下面提到的命令&它从管理员用户组中拉出用户。但在服务器2008 R2中,它从整个域拉动在不同的操作系统中运行powershell脚本
Get-WmiObject -Class Win32_GroupUser `
| where{$_.GroupComponent -like "*Administrators*"} `
|foreach {
$data = $_.PartComponent -split "\,"
$data[1].Remove(0,5).Replace('"','')
}
答
正如你所猜测的问题是,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)发生WH列举这些组。该组织的SID无法解决。
下面的代码是从这里取:https://*.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)