当前位置:网站首页 > 更多 > 玩电脑 > 正文

[玩转系统] 使用 PowerShell 获取本地组成员

作者:精品下载站 日期:2024-12-14 07:48:28 浏览:14 分类:玩电脑

使用 PowerShell 获取本地组成员


最近我发布了一个获取本地用户帐户信息的功能。我收到了很多积极的反馈,因此下一步似乎很自然地创建一个类似的函数来枚举或列出本地组的成员,例如管理员。

Get-LocalGroupMember 函数也依赖于 ADSI,与我的本地用户函数类似,因此我不再重复详细信息。由于我大多数情况下认为唯一重要的本地组是管理员,因此我将其设置为默认组。我还将计算机默认设置为本地主机。但查询另一台计算机就足够简单了。

[玩转系统] 使用 PowerShell 获取本地组成员

您可以通过管道输入计算机名称并使用对象属性进行其他过滤、排序或分组。

"chi-fp02","chi-core01","chi-hvr1","chi-hvr2","chi-web02" | 
get-localgroupmember |
where {$_.IsLocal -AND $_.name -ne 'Administrator'} |
Select Computername,Class,Name

[玩转系统] 使用 PowerShell 获取本地组成员

在此示例中,我想要搜索一组计算机并识别非管理员帐户的本地管理员成员。

与我之前的功能一样,我认为如果您计划查询多个远程服务器或需要使用备用凭据,您会发现使用 PowerShell 远程处理更好。您可以阅读函数帮助以获取更多详细信息。

您始终可以在我的 Github 库中找到该函数的最新版本。

Get-LocalGroupMember.ps1:

#requires -version 4.0

Function Get-LocalGroupMember {

 Get-LocalGroupMember -computer chi-core01

Computername : CHI-CORE01
Name         : Administrator
ADSPath      : WinNT://GLOBOMANTICS/chi-core01/Administrator
Class        : User
Domain       : GLOBOMANTICS
IsLocal      : True

Computername : CHI-CORE01
Name         : Domain Admins
ADSPath      : WinNT://GLOBOMANTICS/Domain Admins
Class        : Group
Domain       : GLOBOMANTICS
IsLocal      : False

Computername : CHI-CORE01
Name         : Chicago IT
ADSPath      : WinNT://GLOBOMANTICS/Chicago IT
Class        : Group
Domain       : GLOBOMANTICS
IsLocal      : False

Computername : CHI-CORE01
Name         : OMAA
ADSPath      : WinNT://GLOBOMANTICS/OMAA
Class        : User
Domain       : GLOBOMANTICS
IsLocal      : False

Computername : CHI-CORE01
Name         : LocalAdmin
ADSPath      : WinNT://GLOBOMANTICS/chi-core01/LocalAdmin
Class        : User
Domain       : GLOBOMANTICS
IsLocal      : True

.EXAMPLE
PS C:\> "chi-hvr1","chi-hvr2","chi-core01","chi-fp02" | get-localgroupmember  | where {$_.IsLocal} | Select Computername,Name,ADSPath

Computername Name          ADSPath                                      
------------ ----          -------                                      
CHI-HVR1     Administrator WinNT://GLOBOMANTICS/chi-hvr1/Administrator  
CHI-HVR2     Administrator WinNT://GLOBOMANTICS/chi-hvr2/Administrator  
CHI-HVR2     Jeff          WinNT://GLOBOMANTICS/chi-hvr2/Jeff           
CHI-CORE01   Administrator WinNT://GLOBOMANTICS/chi-core01/Administrator
CHI-CORE01   LocalAdmin    WinNT://GLOBOMANTICS/chi-core01/LocalAdmin   
CHI-FP02     Administrator WinNT://GLOBOMANTICS/chi-fp02/Administrator

.EXAMPLE
PS C:\> $s = new-pssession chi-hvr1,chi-fp02,chi-hvr2,chi-core01
Create several PSSessions to remote computers.

PS C:\> $sb = ${function:Get-localGroupMember} 

Get the function's scriptblock

PS C:\> Invoke-Command -scriptblock { new-item -path Function:Get-LocalGroupMember -value $using:sb} -session $s 

Create a remote version of the function.

PS C:\> Invoke-Command -scriptblock { get-localgroupmember | where {$_.IsLocal} } -session $s | Select Computername,Name,ADSPath

Repeat an example from above but this time execute it in a remote session.

.EXAMPLE
PS C:\> get-localgroupmember -Name "Hyper-V administrators" -Computername chi-hvr1,chi-hvr2


Computername : CHI-HVR1
Name         : jeff
ADSPath      : WinNT://GLOBOMANTICS/jeff
Class        : User
Domain       : GLOBOMANTICS
IsLocal      : False

Computername : CHI-HVR2
Name         : jeff
ADSPath      : WinNT://GLOBOMANTICS/jeff
Class        : User
Domain       : GLOBOMANTICS
IsLocal      : False

Check group membership for the Hyper-V Administrators group.

.EXAMPLE
PS C:\> get-localgroupmember -Computername chi-core01 | where class -eq 'group' | select Domain,Name

Domain       Name         
------       ----         
GLOBOMANTICS Domain Admins
GLOBOMANTICS Chicago IT   

Get members of the Administrators group on CHI-CORE01 that are groups and select a few properties.


.NOTES
NAME        :  Get-LocalGroupMember
VERSION     :  1.6   
LAST UPDATED:  2/18/2016
AUTHOR      :  Jeff Hicks (@JeffHicks)

Learn more about PowerShell:
http://jdhitsolutions.com/blog/essential-powershell-resources/

  ****************************************************************
  * DO NOT USE IN A PRODUCTION ENVIRONMENT UNTIL YOU HAVE TESTED *
  * THOROUGHLY IN A LAB ENVIRONMENT. USE AT YOUR OWN RISK.  IF   *
  * YOU DO NOT UNDERSTAND WHAT THIS SCRIPT DOES OR HOW IT WORKS, *
  * DO NOT USE IT OUTSIDE OF A SECURE, TEST SETTING.             *
  ****************************************************************

.INPUTS
[string] for computer names

.OUTPUTS
[object]

#>


[cmdletbinding()]

Param(
[Parameter(Position = 0)]
[ValidateNotNullorEmpty()]
[string]$Name = "Administrators",

[Parameter(ValueFromPipeline,ValueFromPipelineByPropertyName)]
[ValidateNotNullorEmpty()]
[Alias("CN","host")]
[string[]]$Computername = $env:computername
)


Begin {
    Write-Verbose "[Starting] $($MyInvocation.Mycommand)"  
    Write-Verbose "[Begin]    Querying members of the $Name group"
} #begin

Process {
 
 foreach ($computer in $computername) {

    #define a flag to indicate if there was an error
    $script:NotFound = $False
    
    #define a trap to handle errors because we're not using cmdlets that
    #could support Try/Catch. Traps must be in same scope.
    Trap [System.Runtime.InteropServices.COMException] {
        $errMsg = "Failed to enumerate $name on $computer. $($_.exception.message)"
        Write-Warning $errMsg

        #set a flag
        $script:NotFound = $True
    
        Continue    
    }

    #define a Trap for all other errors
    Trap {
      Write-Warning "Oops. There was some other type of error: $($_.exception.message)"
      Continue
    }

    Write-Verbose "[Process]  Connecting to $computer"
    #the WinNT moniker is case-sensitive
    [ADSI]$group = "WinNT://$computer/$Name,group"
        
    Write-Verbose "[Process]  Getting group member details" 
    $members = $group.invoke("Members") 

    Write-Verbose "[Process]  Counting group members"
    
    if (-Not $script:NotFound) {
        $found = ($members | measure).count
        Write-Verbose "[Process]  Found $found members"

        if ($found -gt 0 ) {
        $members | foreach {
        
            #define an ordered hashtable which will hold properties
            #for a custom object
            $Hash = [ordered]@{Computername = $computer.toUpper()}

            #Get the name property
            $hash.Add("Name",$_[0].GetType().InvokeMember("Name", 'GetProperty', $null, $_, $null))
        
            #get ADS Path of member
            $ADSPath = $_[0].GetType().InvokeMember("ADSPath", 'GetProperty', $null, $_, $null)
            $hash.Add("ADSPath",$ADSPath)
    
            #get the member class, ie user or group
            $hash.Add("Class",$_[0].GetType().InvokeMember("Class", 'GetProperty', $null, $_, $null))  
    
            

            $hash.Add("Domain",$ADSPath.Split("/")[2])

            #if computer name is found between two /, then assume
            #the ADSPath reflects a local object
            if ($ADSPath -match "/$computer/") {
                $local = $True
                }
            else {
                $local = $False
                }
            $hash.Add("IsLocal",$local)

            #turn the hashtable into an object
            New-Object -TypeName PSObject -Property $hash
         } #foreach member
        } 
        else {
            Write-Warning "No members found in $Name on $Computer."
        }
    } #if no errors
} #foreach computer

} #process

End {
    Write-Verbose "[Ending]  $($MyInvocation.Mycommand)"
} #end

} #end function

您需要 登录账户 后才能发表评论

取消回复欢迎 发表评论:

关灯