Skip to content

Instantly share code, notes, and snippets.

@altrive
Last active August 29, 2015 14:10
Show Gist options
  • Save altrive/6b96c60471d0975387b2 to your computer and use it in GitHub Desktop.
Save altrive/6b96c60471d0975387b2 to your computer and use it in GitHub Desktop.
$ErrorActionPreference = "Stop"

function Main
{
    try
    {
        $logFilePath = 'C:\NotFound.log'
        if (Test-Path $logFilePath)
        {
            throw "Test"
        }
        #$domain = Get-DomainContext
        #$domain.Children.Find("OU={0}" -f "Groups") > $null

        $domain = Get-Domain


        #不要OU削除
        $path = Get-LdapPath -Name "Groups2" -Type OU
        Remove-OU -Name Groups2


        #OUのリネーム
        $path = Get-LdapPath -Name "Groups" -Type OU
        Rename-OU -Path $path -NewName Groups2

        #OUの新規作成
        $path = (Get-Domain).Path
        New-Ou -Path $path -Name Groups
    }
    catch [ApplicationException]
    {
        Write-Error $_
    }
    finally
    {
    }

    <# 
    foreach ($i in 1..100){
        Write-Host ("Add Group $i")
        New-Group -name ("Group" + $i.ToString().PadLeft(4, '0'))
    }
    
    foreach ($i in 1..100){
        Write-Host ("Rename Group $i")
        Rename-Group -name ("Group" + $i.ToString().PadLeft(4, '0')) -NewName ("RenamedGroup" + $i.ToString().PadLeft(4, '0'))
    }
   #>
    <#
    foreach ($i in 1..100){
        Write-Host ("Remove Group $i")
        Remove-Group -name ("Group" + $i.ToString().PadLeft(4, '0'))
    }
    #>
    
}

Add-Type -AssemblyName System.DirectoryServices
Add-Type -AssemblyName System.DirectoryServices.AccountManagement

$script:CachedDomain = $null
$script:DirectoryEntryTemplate = $null

function Get-Domain
{
    if ($script:CachedDomain -ne $null -and (!$script:CachedDomain.Disposed))
    {
        return $script:CachedDomain
    }

    try
    {
        
        try
        {
            $rootDSE = [adsi] "LDAP://localhost/RootDSE"
            $defaultNamingContext = $rootDSE.Properties["defaultNamingContext"][0]
            $domain = [adsi]("LDAP://localhost/{0}" -f $defaultNamingContext)
            $domain.RefreshCache() #Bind
        }
        catch
        {
            $defaultNamingContext = "dc=altrive,dc=net"
            $domain = [adsi]("LDAP://localhost/" + $defaultNamingContext)
        }
        $script:DirectoryEntryTemplate = "LDAP://localhost/{0},$defaultNamingContext"
        
        $script:CachedDomain = $domain

        return $domain
    }
    finally
    {
        <#
        if ($rootDSE -ne $null){
            $rootDSE.Dispose()
        }
        #>
    }
}


function New-OU
{
    param (
        [string] $Path,
        [string] $Name
    )


    try
    {
        $container = [adsi] $Path
        $container.RefreshCache() #Bind
        $container.Children.Add("OU=$Name", "OrganizationalUnit")
        $ou.CommitChanges();
    }
    catch
    {
        Write-Error $_
        throw New-Object ApplicationException("Failed to create OU:$Name")
    }
}


function Remove-OU
{
    param (
        [string] $Name
    )
    $domain = Get-Domain

    $path = $script:DirectoryEntryTemplate -f "OU=$Name"
    if (![adsi]::Exists($path))
    {
        return
    }

    try
    {
        $ou = [adsi] $path
        $ou.RefreshCache() > $null

        #Everyone拒否権限を削除
        $everyoneSid = New-Object Security.Principal.SecurityIdentifier([Security.Principal.WellKnownSidType]::WorldSid, $null)
        $ou.ObjectSecurity.RemoveAccess($everyoneSid, [System.Security.AccessControl.AccessControlType]::Deny)

        #OU削除
        $ou.DeleteTree()
    }
    catch
    {
        throw
    }
    finally
    {
        if ($ou -ne $null){
            $ou.Dispose()
        }
    }
}

function Get-LdapPath
{
    param (
        [Parameter(Mandatory)]
        [string] $Name,
        [Parameter(Mandatory)]
        [ValidateSet("OU", "Group", "User", "DomainRoot")]
        [string] $Type
    )
    switch ($Type)
    {
        "OU"{
            return $script:DirectoryEntryTemplate -f ("OU=$Name")
        }
        "Group"{
            return $script:DirectoryEntryTemplate -f ("CN=$Name")
        }
        "User"{
            return $script:DirectoryEntryTemplate -f ("CN=$Name")
        }
        default
        {
            throw "Not Expected Type:$Type"
        }
    }
    
}

function Rename-OU
{
    param (
        [string] $Path,
        [string] $NewName
    )
    
    if (![adsi]::Exists($path)){
        return
    }
    #$container = [adsi]("LDAP://localhost:389/OU={0}, dc=altrive, dc=net" -f "Groups")
    $ou = [adsi] $path
    $ou.Rename("OU={0} " -f $NewName)
    $ou.CommitChanges()
    $ou.Dispose()
}

Main
<#
$ctx = [System.DirectoryServices.ActiveDirectory.DirectoryContext]::new([System.DirectoryServices.ActiveDirectory.DirectoryContextType]::DirectoryServer," LDAP://localhost:389/dc=altrive, dc=net")
 $ctx = New-Object DirectoryServices.AccountManagement.PrincipalContext([System.DirectoryServices.AccountManagement.ContextType]::Machine, "alt-PC");
 
$sb = New-Object Text.StringBuilder 
$d = [System.DirectoryServices.ActiveDirectory.Domain]::GetDomain($ctx)
#>

<#
$list = $ou.Children | foreach { $_.distinguishedName; $_.Dispose()}
foreach ($group in $list)
{
    
}
#>


<#


function New-Group
{
    param (
        [string] $Name
    )
    $container = [adsi] "LDAP://localhost:389/ou=Groups, dc=altrive, dc=net"
    $container.RefreshCache()
    $group = $container.Create("Group", "CN={0} " -f $Name)
    $group.CommitChanges()
    $container.CommitChanges()
    $container.dispose()
    $group.Dispose()
}

function Remove-Group
{
    param (
        [string] $Name
    )

    $container = [adsi]("LDAP://localhost:389/ou=Groups, dc=altrive, dc=net")

    $path = [adsi]("LDAP://localhost:389/CN={0}, ou=Groups, dc=altrive, dc=net" -f $Name)
    $container.Children.Remove($path)
    $management.CommitChanges()
}

function Rename-Group
{
    param (
        [string] $Name,
        [string] $NewName
    )
    
    if (![adsi]::Exists(("LDAP://localhost:389/CN={0},OU=Groups,dc=altrive, dc=net" -f $Name))){
        Write-Host "Don't exists:$Name"
    }
    #$container = [adsi]("LDAP://localhost:389/OU={ 0 }, dc=altrive, dc=net" -f "Groups")
    $ou = [adsi]("LDAP://localhost:389/CN={0},OU=Groups,dc=altrive, dc=net" -f $Name)
    $ou.Rename("CN={0} " -f $NewName)
    $ou.CommitChanges()
    $ou.Dispose()
}
#>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment