2009-09-09 3 views
0

나는 셰어 포인트 서비스에 해당 이름을 기반으로 그룹을 채우려면 모든 CN의 활성 디렉토리를 확보하려고합니다.Active Directory 필터 memberof

$Dom = 'LDAP://OU=External,OU=Users,OU=HomeOffice,DC=mydoman,DC=com' 
$Root = New-Object DirectoryServices.DirectoryEntry $Dom 
$i=0 
# Create a selector and start searching from the Root of AD 
$selector = New-Object DirectoryServices.DirectorySearcher 
$selector.SearchRoot = $root 
$adobj= $selector.findall() |` 
where {$_.properties.objectcategory -match "CN=Person"} 
foreach ($person in $adobj){ 
    $prop=$person.properties 
    $i++ 
    Write-host "$($prop.department) - $($prop.sn), $($prop.givenname)" 
    Write-host $person.properties["memberof"] 
} 
"Total $i" 

지금 내가 필요한 모든 것을 얻을,하지만 난 단지 CN의 출력을 필터링 할 수있는 방법이 필요합니다 (",") 나는 "의 memberOf"절을 나열 할 수 있지만 분할을 사용하여 분할 할 수없는 것 ..

+0

좋아 그렇게 사용 난 그냥 CN의 를 ForEach-오브젝트 {$ 테스트 -replace를 필터링 할 수 있어요이 "OU = BLAH" ","-replace ",", "'r'n"} 그러나 어떤 이유로 난 여전히 두 번 모두를 받고 첫 세트를 구문 분석 할 경우에만 수 있어요 CN = 그룹 1 CN = 그룹 2 CN = 그룹 3 CN = 그룹 4 CN = 그룹 1, OU는 = 그룹, OU = 사무실, DC는 사용자 도메인, DC = COM CN = 그룹 2, OU는 = 그룹, OU = 사무실을 =, DC는 사용자 도메인, DC = COM CN을 = = 그룹 3, OU = 그룹, OU = 사무실, DC = mydomain, DC = com CN = Group4, OU = 그룹, OU = 사무실, DC = mydomain, DC = com –

답변

0

test1.ps1

#Connet using LDAP 
$Dom = 'LDAP://OU=External Accounts,OU=Users,OU=The Office,DC=mydomain,DC=com' 
$Root = New-Object DirectoryServices.DirectoryEntry $Dom 

#Integer for the loop 
$i=0 

# Create a selector and start searching from the Root of AD 
$selector = New-Object DirectoryServices.DirectorySearcher 
$selector.SearchRoot = $root 

#Find the Groups 
$adobj= $selector.findall() |` 
where {$_.properties.objectcategory -match "CN=Person"} 
foreach ($person in $adobj){ 
    $prop=$person.properties 
    $i++ 
    #Write-host "$($prop.department) - $($prop.sn), $($prop.givenname)" -foregroundcolor Magenta 
    $test = $person.properties["memberof"] 
    ForEach-Object { 
     $test` 
     -replace "CN=OLDLEGACYGROUP",""` 
     -replace "CN=",""` 
     -replace ",OU=Sales",""` 
     -replace ",OU=Some Groups",""` 
     -replace ",OU=Groups","" ` 
     -replace ",OU=The Office","" ` 
     -replace ",DC=mydomain","" ` 
     -replace ",DC=com","" ` 
     -replace ",","`r`n" 
    } 
} 

test2.ps1

# Lets start with a clean slate :) 
Clear 

# Lets reference the assembly/GAC that we need for this 
#region 
[Void][System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint") 
$SPSite = New-Object Microsoft.SharePoint.SPSite("https://myintranetorextranetsite.myfqdn.com") 
$OpenWeb = $SpSite.OpenWeb("/") 
#endregion 

# Add some eye candy :) 
# region 
# I really wanted some old school thing in here :) 
write-host " _ ____  ____     " -foregroundcolor Magenta 
write-host " /\ | _ \ /___| _ _ _ __ ___ " -foregroundcolor Magenta 
write-host "/_ \ | | | |____\___ \| | | | '_ \/__|" -foregroundcolor Magenta 
write-host "/___ \| |_| |_____|__) | |_| | | | | (__ " -foregroundcolor Magenta 
write-host "|_/ \_\____/  |____/ \__, |_| |_|\___|" -foregroundcolor Magenta 
write-host "       |___/   " -foregroundcolor Magenta 
Write-Host " Version 2.0" -foregroundcolor Red 
Write-Host " Build 2009 09-11 21:30" -foregroundcolor Red 
Write-host " Created by Mitchell J. Skurnik" -foregroundcolor Red 
#endregion 

# Create the stopwatch 
#region 
[System.Diagnostics.Stopwatch] $sw; 
$sw = New-Object System.Diagnostics.StopWatch 
$sw.Stop() 
$sw.Start() 
#endregion 

# Function to control Adding groups 
function creategroup 
{ 
    param ([string] $siteurl = "https://myintranetorextranetsite.myfqdn.com") 
    $site = New-Object Microsoft.SharePoint.SPSite($siteurl) 
    $web = $site.RootWeb; 
    $group = $currentgroup; 
    $perm = "Read"; 
    $owner = "jdoe"; 
    if ($owner -eq "") { $owner = $web.CurrentUser.LoginName } 

    $exists = $web.SiteGroups | where { $_.Name -eq $group } 
    if ($exists -eq $null) 
    { 
     # Create group 
     $web.SiteGroups.Add($group, $web.EnsureUser($owner), $null, ""); 
     # Give permissions to the group 
     $assign = New-Object Microsoft.SharePoint.SPRoleAssignment($web.SiteGroups[$group]); 
     $assign.RoleDefinitionBindings.Add($web.RoleDefinitions[$perm]) 
     $web.RoleAssignments.Add($assign) 
     Write-Host -ForegroundColor green "Creating sharepoint group - " $currentgroup; 
    } 
    $site.Dispose(); 
} 

# Function to add users to the specified group 
function addUser 
{ 
    # Open a connection to the sharepoint site and then select the sub site you want 
    $themail = $prop.mail 
    $thedisplay = $prop.displayname 

    # If there are accounts that dont have some info lets populate it 
    if ($themail -eq "") 
    { 
     $themail = "[email protected]" 
    } 
    if ($thedisplay -eq "") 
    { 
     $thedisplay = "Account, Test" 
    } 
    if ($themail -eq $null) 
    { 
     $themail = "[email protected]" 
    } 
    if ($thedisplay -eq $null) 
    { 
     $thedisplay = "Account, Test" 
    } 
    $TheNewGroup = $OpenWeb.SiteGroups | Where-Object {$_.Name -match $currentGroup} 
    $TheNewGroup.AddUser("NTAMR\" + $prop.samaccountname,$themail,$prop.displayname,"") 
    #write-host "Added: " $thedisplay -foregroundcolor Red 
} 

# Function to remove people - be careful using this script :(
# Also not done 
function removeUser 
{ 
    #$TheNewGroup = $OpenWeb.SiteGroups | Where-Object {$_.Name -match $currentGroup} 
    #$TheNewGroup.AddUser("NTAMR\" + $prop.samaccountname,$themail,$prop.displayname,"") 
    #$TheNewGroup.Remove($LoginToDel) 
} 

# Now onto the real stuff 
Write-host "Searching for Groups" -foregroundcolor Green 

# Clear out the existing text file so we have a clean slate 
$file = New-Item -type file "C:\location\to\my\folder\allGroups.txt" -Force 

# Execute the Group Dump Script 
C:\location\to\my\folder\test.ps1 | Out-File -filepath "C:\location\to\my\folder\allGroups.txt" -append 

# Clean up the list by removing duplicates and sorting everything 
$TextFile = $TextFile = "C:\Powershell\allGroups.txt" 
$NewTextFile = "C:\Powershell\allGroups - Sorted.txt" 
GC $TextFile | Sort | GU > $NewTextFile 

# Use LDAP to connect to Active Directory 
#region 
$Dom = 'LDAP://OU=External Accounts,OU=Users,OU=The Office,DC=mydomain,DC=com' 
$Root = New-Object DirectoryServices.DirectoryEntry $Dom 
#endregion 

# Create a selector and start searching from the Root of AD 
#region 
$selector = New-Object DirectoryServices.DirectorySearcher 
$selector.SearchRoot = $root 
#endregion 

# Integer to compare file length 
$c=0 

# Get the Group text file's length and write to scree and variable 
$fileLength = [System.IO.File]::ReadAllText($NewTextFile).Split("`n").Count 
Write-Host "Found " $fileLength "Groups in Active Directory" -foregroundcolor Magenta 

# Integer for thumbing through 'memberOf' in active directory 
$d = 0 

# Integer for the amount of of users found 
$f = 0 

# Start a while loop where we read through the entire groups text file 
while ($c -le $fileLength) 
{ 
    # Increment the line number for the next pass through 
    $c++ 

    # Grab the first line of text from the groups file (Really the 0th line) and then tell the user 
    $currentGroup = (Get-Content $NewTextFile)[$c] 

    # Create the group 
    CreateGroup 
    #Write-Host "Created Group: " $currentGroup -foregroundcolor Red 

    # 
    Write-host $c "/" $fileLength "`t" $currentGroup -foregroundcolor Red 

    # Query Active directory and force some commands 
    $adobj= $selector.findall() | where {$_.properties.objectcategory -match "CN=Person"} 
    foreach ($person in $adobj) 
    { 
     # Variable for the different properties to reduce fatigue 
     $prop=$person.properties 

     # The Department 
     $department = $prop.department 

     # Sir Name 
     $sn = $prop.sn 

     # Given Name 
     $gn = $prop.givenname 

     $un = $prop.samaccountname 

     # Assign the really long memberof to a variable 
     $memberof = $person.properties["memberof"] 

     # Length of memberof 
     $memberofcount = $test.Count 


     # Loop for each group the member is in 
     while ($d -le $memberof.Count) 
     { 
      $blah = ForEach-Object{` 
       $memberof[$d]` 
       -replace "CN=OLDLEGACYGROUP",""` 
       -replace "CN=",""` 
       -replace ",OU=Sales",""` 
       -replace ",OU=Some Groups",""` 
       -replace ",OU=Groups","" ` 
       -replace ",OU=The Office","" ` 
       -replace ",DC=mydomain","" ` 
       -replace ",DC=com","" ` 
      } 
      # Incriment the d 
      $d++ 

      # Is that user in the group? 
      if ($blah -eq $currentGroup) 
      { 
       # Hey look we found somebody in that group :) 
       Write-host "`t`t`t" $un -foregroundcolor Magenta 
       addUser 
       $f++ 
      } 
      #elseif ($blah -ne $currentGroup) 
      #{ 
      # removeUser 
      #} 

      else 
      { 
       # Oh noes...nobody is in that group...that is strange 
      } 
     } 


     # Are we at the end of what the user has 
     if ($d -ge $memberofs.Count) 
     { 
      # Looks like we are :) 
      $d=0 
     } 
    } 

    # Display amount of users found 
    #Write-Host "`t`t`t" $f " user(s) found" 
    $f = 0 
} 

# Stop Watch 
$sw.Stop() 

# Write the compact output to the screen 
write-host "Updated in Time: ", $sw.Elapsed.ToString() 


#This space is saved for future development 
+0

사용자가 이미 해당 그룹의 공유 폴더에 있는지 확인하고 스크립트를 삭제하지 않아도되는지 확인하기위한 스크립트 부분을 얻을 기회가 없었습니다 그에게서 그. 방금 9:00에 어제 끝냈습니다 –

+0

참고 다음 사이트에서 코드 일부를 사용하고 있습니다 : http://www.codeplex.com/SharePointPSScripts/ 및 http://www.powershell.nu –

+0

I 이 작업을 수행 할 때 가장 가까운 것으로 유용하다고 생각 하시길 바랍니다. 대나무 솔루션으로 800 달러였습니다. 모두 완료하는 데 약 24 시간이 걸렸다. 그리고 내가 전에 말했듯이,이 스크립트는 내 첫 번째 파워 쉘 스크립트이다. –

1

일반적으로 쓰기 호스트는 출력을 생성하는 가장 좋은 방법은 아닙니다. 이상적으로는 함수에서 개체를 내보내고 PowerShell에서 형식을 지정하게하는 것이 좋습니다. 이것은 일을하는 "파이프 라인 친화적 인"방법입니다. 이 경우, 경우 트릭은 새로운 객체를 만들고 여기에 속성을 추가하거나 그냥 DirectoryServices 이미 당기는 객체 방출되는

Get-Person | ft CN 

같은 당신이 파이프 할 수있는 기능은 Get-GroupMembers했다. 새로운 사용자 지정 개체를 만들려면 다음을 수행 할 수 있습니다

$obj = new-object psobject 
$obj | add-member -membertype noteproperty name $PropName -value $valueToStore 

사람들은이 형식의 테이블 형식 목록, 그룹 개체 정렬 개체 및 다양한 객체를 선택하는 당신의 기능과 파이프를 사용할 수 있습니다 다른 것들. Keith Hill의 Effective PowerShell은 도움이 될 수있는 훌륭한 chapter on Output을 가지고 있습니다.

Don Jones on using objects instead of text에 의한 기사도 꽤 있습니다.

+0

감사합니다. 이것이 필자가 생각하기에 좋은 시작이라고 생각하는 powershell 스크립트를 작성한 나의 두 번째 시도이다. Don Jones는 그 값을 출력하는 좋은 방법을 보여줍니다. 나는 미래를 위해 그런 방법을 들여다 보겠지만 지금은 대본을 그대로 남겨 둘 것입니다. 400 개의 다른 그룹에 약 400 명의 사람들을 삽입하는 데 약 30 분이 걸립니다. –