Powershell About LocalGroupMembership

一: 结合active directory获取本地群组成员信息(包含本地用户和域用户,及域用户的情况

$DBServer = "xxxx"
$DBDatabase = "xxxx"
#$table="UserInfo"
$Connection = New-Object System.Data.SQLClient.SQLConnection
$Connection.ConnectionString = "server='$DBServer';database='$DBDatabase';trusted_connection=true;"
$Connection.Open()
$Command = New-Object System.Data.SQLClient.SQLCommand
$Command.Connection = $Connection

$AllServer=Get-ADComputer -SearchScope subtree -SearchBase "ou=xxxx,dc=xxx,dc=xxx,dc=xxxx" -filter * -properties * | where {$_.Enabled -eq $true}
 
foreach($Server in $AllServer)
 {
$ComputerName=""
$ipv4Address=""
$operatingsystem=""
$whenCreated=""
$LastLogonDate=""
$Path_S = ""
$ComputerName=$Server.Name
$ipv4Address=$server.IPV4Address
#echo "$computername is $ipv4Address"
$operatingsystem=$server.operatingsystem
$whenCreated=$server.whenCreated
$LastLogonDate=$server.LastLogonDate
$Pingy = Get-WmiObject Win32_PingStatus -f "Address='$ComputerName'" 
    if($Pingy.StatusCode -eq 0)
        {
        $errorcount=$error.count
        $GroupName="Administrators"
        $results=Get-LocalGroupMembership -ComputerName $ComputerName -GroupName "Administrators"
        if($errorcount -eq $error.Count)
            { 
            $info="OK"

             Foreach($result in $results)
                    {
                    $ComputerName=$ComputerName
                    $Path=$result.Path -replace “^.*:”
                    if($Path -like "*S-1-5-21*")
                        {
                        $Path=" "
                        }
                     $Path_S = $Path_S+$Path + ";"
                    }
                  
                    echo "$Path_S"
                

               }
        else
            {
             $info="error"
            echo "$ComputerName is  $info"
            }

        }

   else{
   $info="notavailable"
        echo "$ComputerName is $info "
        }
$insert="insert into LocalMembership(ComputerName,ipv4address,operatingsystem,whenCreated,LastLogonDate,info,account,accountstatus,class,groupname,path,type) values(N'$ComputerName',N'$ipv4Address',N'$operatingsystem',N'$whenCreated',N'$LastLogonDate',N'$info',N'$account1',N'$accountstatus1',N'$class1',N'$groupname',N'$Path_S',N'$type1')" 
$cmd=new-object system.Data.SqlClient.SqlCommand($insert,$Connection) 
$cmd.CommandTimeout=6000
$cmd.ExecuteNonQuery()
 }

 

 

 

二、#Function Get-LocalGroupMembership

Function Get-LocalGroupMembership {
<#
.Synopsis
    Get the local group membership.      
.Description
    Get the local group membership.       
.Parameter ComputerName
    Name of the Computer to get group members. Default is "localhost".     
.Parameter GroupName
    Name of the GroupName to get members from. Default is "Administrators".        
.Example
    Get-LocalGroupMembership
    Description
    -----------
    Get the Administrators group membership for the localhost     
.Example
    Get-LocalGroupMembership -ComputerName SERVER01 -GroupName "Remote Desktop Users"
    Description
    -----------
    Get the membership for the the group "Remote Desktop Users" on the computer SERVER01
.Example
    Get-LocalGroupMembership -ComputerName SERVER01,SERVER02 -GroupName "Administrators"
    Description
    -----------
    Get the membership for the the group "Administrators" on the computers SERVER01 and SERVER02
.OUTPUTS
    PSCustomObject      
.INPUTS
    Array          
.Link
    N/A     
.Notes
    NAME:      Get-LocalGroupMembership
    AUTHOR:    Francois-Xavier Cat
    WEBSITE:   www.LazyWinAdmin.com
#>
 [Cmdletbinding()]
 PARAM (
        [alias('DnsHostName','__SERVER','Computer','IPAddress')]
  [Parameter(ValueFromPipelineByPropertyName=$true,ValueFromPipeline=$true)]
  [string[]]$ComputerName = $env:COMPUTERNAME,
  [string]$GroupName = "Administrators"
  )
    BEGIN{
    }#BEGIN BLOCK
    PROCESS{
        foreach ($Computer in $ComputerName){
            TRY{
                $Everything_is_OK = $true
                # Testing the connection
                Write-Verbose -Message "$Computer - Testing connection..."
                Test-Connection -ComputerName $Computer -Count 1 -ErrorAction Stop |Out-Null    
                # Get the members for the group and computer specified
                Write-Verbose -Message "$Computer - Querying..."
             $Group = [ADSI]"WinNT://$Computer/$GroupName,group"
             $Members = @($group.psbase.Invoke("Members"))
            }#TRY
            CATCH{
                $Everything_is_OK = $false
                Write-Warning -Message "Something went wrong on $Computer"
                Write-Verbose -Message "Error on $Computer"
                }#Catch
            IF($Everything_is_OK){
             # Format the Output
                Write-Verbose -Message "$Computer - Formatting Data"
             $members | ForEach-Object {
              $name = $_.GetType().InvokeMember("Name", 'GetProperty', $null, $_, $null)
              $class = $_.GetType().InvokeMember("Class", 'GetProperty', $null, $_, $null)
              $path = $_.GetType().InvokeMember("ADsPath", 'GetProperty', $null, $_, $null)
              # Find out if this is a local or domain object
              if ($path -like "*/$Computer/*"){
               $Type = "Local"
               }
              else {$Type = "Domain"
              }
              $Details = "" | Select-Object ComputerName,Account,Class,Group,Path,Type
              $Details.ComputerName = $Computer
              $Details.Account = $name
              $Details.Class = $class
                    $Details.Group = $GroupName
              $details.Path = $path
              $details.Type = $type
              # Show the Output
                    $Details
             }
            }#IF(Everything_is_OK)
        }#Foreach
    }#PROCESS BLOCK
    END{Write-Verbose -Message "Script Done"}#END BLOCK
}#Function Get-LocalGroupMembership
View Code

 

三、Set-ADAccountasLocalAdministrator.ps1

([ADSI]"WinNT://$_/Administrators,group").add($Trustee)
<#
.SYNOPSIS   
Script to add an AD User or group to the Local Administrator group
    
.DESCRIPTION 
The script can use either a plaintext file or a computer name as input and will add the trustee (user or group) as an administrator to the computer
    
.PARAMETER InputFile
A path that contains a plaintext file with computer names

.PARAMETER Computer
This parameter can be used instead of the InputFile parameter to specify a single computer or a series of
computers using a comma-separated format
    
.PARAMETER Trustee
The SamAccount name of an AD User or AD Group that is to be added to the Local Administrators group

.NOTES   
Name: Set-ADAccountasLocalAdministrator.ps1
Author: Jaap Brasser
Version: 1.1
DateCreated: 2012-09-06
DateUpdated: 2013-07-23

.LINK
http://www.jaapbrasser.com

.EXAMPLE   
.\Get-Set-ADAccountasLocalAdministrator.ps1.ps1 -Computer Server01 -Trustee JaapBrasser

Description:
Will set the the JaapBrasser account as a Local Administrator on Server01

.EXAMPLE   
.\Get-Set-ADAccountasLocalAdministrator.ps1.ps1 -Computer 'Server01,Server02' -Trustee Contoso\HRManagers

Description:
Will set the HRManagers group in the contoso domain as Local Administrators on Server01 and Server02

.EXAMPLE   
.\Set-ADAccountasLocalAdministrator.ps1 -InputFile C:\ListofComputers.txt -Trustee User01

Description:
Will set the User01 account as a Local Administrator on all servers and computernames listed in the ListofComputers file
#>
param(
    [Parameter(ParameterSetName='InputFile')]
    [string]
        $InputFile,
    [Parameter(ParameterSetName='Computer')]
    [string]
        $Computer,
    [string]
        $Trustee
)
<#
.SYNOPSIS
    Function that resolves SAMAccount and can exit script if resolution fails
#>
function Resolve-SamAccount {
param(
    [string]
        $SamAccount,
    [boolean]
        $Exit
)
    process {
        try
        {
            $ADResolve = ([adsisearcher]"(samaccountname=$Trustee)").findone().properties['samaccountname']
        }
        catch
        {
            $ADResolve = $null
        }

        if (!$ADResolve) {
            Write-Warning "User `'$SamAccount`' not found in AD, please input correct SAM Account"
            if ($Exit) {
                exit
            }
        }
        $ADResolve
    }
}

if (!$Trustee) {
    $Trustee = Read-Host "Please input trustee"
}

if ($Trustee -notmatch '\\') {
    $ADResolved = (Resolve-SamAccount -SamAccount $Trustee -Exit:$true)
    $Trustee = 'WinNT://',"$env:userdomain",'/',$ADResolved -join ''
} else {
    $ADResolved = ($Trustee -split '\\')[1]
    $DomainResolved = ($Trustee -split '\\')[0]
    $Trustee = 'WinNT://',$DomainResolved,'/',$ADResolved -join ''
}

if (!$InputFile) {
    if (!$Computer) {
        $Computer = Read-Host "Please input computer name"
    }
    [string[]]$Computer = $Computer.Split(',')
    $Computer | ForEach-Object {
        $_
        Write-Host "Adding `'$ADResolved`' to Administrators group on `'$_`'"
        try {
            ([ADSI]"WinNT://$_/Administrators,group").add($Trustee)
            Write-Host -ForegroundColor Green "Successfully completed command for `'$ADResolved`' on `'$_`'"
        } catch {
            Write-Warning "$_"
        }    
    }
}
else {
    if (!(Test-Path -Path $InputFile)) {
        Write-Warning "Input file not found, please enter correct path"
        exit
    }
    Get-Content -Path $InputFile | ForEach-Object {
        Write-Host "Adding `'$ADResolved`' to Administrators group on `'$_`'"
        try {
            ([ADSI]"WinNT://$_/Administrators,group").add($Trustee)
            Write-Host -ForegroundColor Green "Successfully completed command"
        } catch {
            Write-Warning "$_"
        }        
    }
}
View Code

 

四、remove-ADAccountasLocalAdministrator.ps1

([ADSI]"WinNT://$_/Administrators,group").remove($Trustee)

 

<#
.SYNOPSIS   
Script to add an AD User or group to the Local Administrator group
    
.DESCRIPTION 
The script can use either a plaintext file or a computer name as input and will add the trustee (user or group) as an administrator to the computer
    
.PARAMETER InputFile
A path that contains a plaintext file with computer names

.PARAMETER Computer
This parameter can be used instead of the InputFile parameter to specify a single computer or a series of
computers using a comma-separated format
    
.PARAMETER Trustee
The SamAccount name of an AD User or AD Group that is to be added to the Local Administrators group

.NOTES   
Name: Set-ADAccountasLocalAdministrator.ps1
Author: Jaap Brasser
Version: 1.1
DateCreated: 2012-09-06
DateUpdated: 2013-07-23

.LINK
http://www.jaapbrasser.com

.EXAMPLE   
.\Get-Set-ADAccountasLocalAdministrator.ps1.ps1 -Computer Server01 -Trustee JaapBrasser

Description:
Will set the the JaapBrasser account as a Local Administrator on Server01

.EXAMPLE   
.\Get-Set-ADAccountasLocalAdministrator.ps1.ps1 -Computer 'Server01,Server02' -Trustee Contoso\HRManagers

Description:
Will set the HRManagers group in the contoso domain as Local Administrators on Server01 and Server02

.EXAMPLE   
.\remove-ADAccountasLocalAdministrator.ps1 -InputFile C:\ListofComputers.txt -Trustee User01

Description:
Will set the User01 account as a Local Administrator on all servers and computernames listed in the ListofComputers file
#>
param(
    [Parameter(ParameterSetName='InputFile')]
    [string]
        $InputFile,
    [Parameter(ParameterSetName='Computer')]
    [string]
        $Computer,
    [string]
        $Trustee
)
<#
.SYNOPSIS
    Function that resolves SAMAccount and can exit script if resolution fails
#>
function Resolve-SamAccount {
param(
    [string]
        $SamAccount,
    [boolean]
        $Exit
)
    process {
        try
        {
            $ADResolve = ([adsisearcher]"(samaccountname=$Trustee)").findone().properties['samaccountname']
        }
        catch
        {
            $ADResolve = $null
        }

        if (!$ADResolve) {
            Write-Warning "User `'$SamAccount`' not found in AD, please input correct SAM Account"
            if ($Exit) {
                exit
            }
        }
        $ADResolve
    }
}

if (!$Trustee) {
    $Trustee = Read-Host "Please input trustee"
}

if ($Trustee -notmatch '\\') {
    $ADResolved = (Resolve-SamAccount -SamAccount $Trustee -Exit:$true)
    $Trustee = 'WinNT://',"$env:userdomain",'/',$ADResolved -join ''
} else {
    $ADResolved = ($Trustee -split '\\')[1]
    $DomainResolved = ($Trustee -split '\\')[0]
    $Trustee = 'WinNT://',$DomainResolved,'/',$ADResolved -join ''
}

if (!$InputFile) {
    if (!$Computer) {
        $Computer = Read-Host "Please input computer name"
    }
    [string[]]$Computer = $Computer.Split(',')
    $Computer | ForEach-Object {
        $_
        Write-Host "Removing `'$ADResolved`' to Administrators group on `'$_`'"
        try {
            ([ADSI]"WinNT://$_/Administrators,group").remove($Trustee)
            Write-Host -ForegroundColor Green "Successfully completed command for `'$ADResolved`' on `'$_`'"
        } catch {
            Write-Warning "$_"
        }    
    }
}
else {
    if (!(Test-Path -Path $InputFile)) {
        Write-Warning "Input file not found, please enter correct path"
        exit
    }
    Get-Content -Path $InputFile | ForEach-Object {
        Write-Host "Removing `'$ADResolved`' to Administrators group on `'$_`'"
        try {
            ([ADSI]"WinNT://$_/Administrators,group").remove($Trustee)
            Write-Host -ForegroundColor Green "Successfully completed command"
        } catch {
            Write-Warning "$_"
        }        
    }
}
View Code

 

posted @ 2017-06-27 09:46  寻香径  阅读(373)  评论(0编辑  收藏  举报