使用PowerShell从本地组中获取域用户

时间:2018-05-30 07:10:02

标签: powershell server usergroups

我想从一台服务器迁移到另一台服务器,因此需要在新服务器中添加一些本地组。在这些本地组中,添加的用户属于域。

例如:

          Server           | Members

---------------------------|------------------

Server\Group1              | Domain\User1, Domain\User2
Server\Group2              | Domain\User2, Domain\User3

以下链接https://www.petri.com/use-powershell-to-find-local-groups-and-members似乎可以解决此问题,但我收到了意外结果

这是PowerShell脚本

# set variables
$server = $env:COMPUTERNAME
$localgroup = "Administrators"
$Group= [ADSI]"WinNT://$Server/$LocalGroup,group"

# get users name
$members = $Group.psbase.Invoke("Members")
$members | ForEach-Object 
{ 
    $_.GetType().InvokeMember("Name", 'GetProperty', $null, $_, $null) 
}

Get-WMIObject win32_group -filter "LocalAccount='True'" -computername $Server | Select PSComputername,Name,@{Name="Members";Expression={$_.GetRelated("Win32_UserAccount").Name -join ";"}}

显示的输出是两列(虽然它应该是3,但{} <}没有显示成员列为空的位置

1 个答案:

答案 0 :(得分:0)

嗯,这就是我实现输出的方法,并将其导出到* .csv文件

# set variables
$server = $env:COMPUTERNAME

$tableOutput = New-Object System.Collections.ArrayList

# get members
Function Get-Members($groupName){
    $testgroup = [ADSI]"WinNT://$Server/$tmpGroupName,group"
    $members = New-Object System.Collections.ArrayList
    $testgroup.psbase.Invoke("Members") | ForEach-Object{
    $searchFilter = $_.GetType().InvokeMember("Name", 'GetProperty', $null, $_, $null) -replace "\."," "
        $tmpUser = Get-ADUser -Filter {(Name -like $searchFilter) -or (SamAccountName -like $searchFilter)}
        if($tmpUser){
            [void]$members.Add($tmpUser.UserPrincipalName)
        }
    }       
    $members
}

Get-WMIObject win32_group -Filter { (LocalAccount='True') } -computername $Server | ForEach-Object{         
    $tmpGroup = $_ 

    # get data
    $tmpGroupName = $tmpGroup.Name
    $members = Get-Members($tmpGroupName)             
    $tmpGroupDescription = $tmpGroup.Description        

    # save into object        
    $groupObject = New-Object -TypeName PSObject
    $groupObject | Add-Member -MemberType NoteProperty -Name GroupName -Value $tmpGroupName
    $groupObject | Add-Member -MemberType NoteProperty -Name GroupDescription -Value $tmpGroupDescription
    $groupObject | Add-Member -MemberType NoteProperty -Name UsersList -Value $members      

    [void]$tableOutput.Add($groupObject)
}

$tableOutput | Select GroupName, GroupDescription, @{Name='Users';Expression={$_.UsersList -join ','}} | Export-CSV -Path 'C:\test\users.csv' -Delimiter ';' -NoTypeInformation

任何更正都将受到赞赏。