1

I want to migrate from one server to another one and because of that it is needed to add some local groups in the new server. In these local groups the users added belong to the domain.

Ex.:

          Server           | Members

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

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

The following link https://www.petri.com/use-powershell-to-find-local-groups-and-members seems to resolve this, but I am getting an unexpected result

This is the PowerShell script

# 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 ";"}}

The shown output is a two columns(although it should be 3, but PSComputerName is not being displayed where the Members column is empty)

blfuentes
  • 2,731
  • 5
  • 44
  • 72

1 Answers1

0

Well, this is how I achieved the output and also exported it to a *.csv file

# 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

Any correction would be appreciated.

blfuentes
  • 2,731
  • 5
  • 44
  • 72