PSAdsi-Convert.psm1

function Convert-AdsiUsers {
    <#
        .SYNOPSIS
            Converti des object ADSI et PSCustomObject
        .DESCRIPTION
            recupere les info de principale
        .PARAMETER Items
             
        .EXAMPLE
            Convert-AdsiUsers
        .NOTES
            Alban LOPEZ 2019
            alban.lopez@gmail.com
            http://git/PowerTech/
    #>

    [CmdletBinding()]
    param (
        [Parameter(ValueFromPipeline=$true)]$Items,
        [switch]$full
    )
    begin {
    }
    process {
        foreach ($item in $items) {
            try {
                $AdsiItem = $item | ForEach-Object{[adsi]$_.path}
                # write-host -ForegroundColor Green (Measure-Command {
                    try {
                        if($AdsiItem.InvokeGet("AllowLogon") -ne $false) {
                            $TsAllowLogon = 'RD Session'
                        } elseif ($AdsiItem.mail) {
                            $TsAllowLogon = 'Bal Only'
                        } else {
                            $TsAllowLogon = 'Just Account'
                        }
                    } catch {$TsAllowLogon = 'RD Session'} # n'as jamais été défini pour ce User
                    # Write-Color '[',$item.invokeget('mstsallowlogon'),' vs ',$AdsiItem.invokeget('mstsallowlogon'),' vs ',$TsAllowLogon,']' -fore white,Magenta,Cyan,Yellow,Cyan,Green,white
                    if (($AdsiItem.userAccountControl.value -band 0x02)) {$state ='Disabled'} else {$state = ''}
                # }).TotalSeconds
                # write-host -ForegroundColor cyan (Measure-Command {
                    try {
                        $sid = (New-Object Security.Principal.SecurityIdentifier( $AdsiItem.objectSid.Value, 0)).Value
                    } catch {$sid = $null}
                # }).TotalSeconds
                # write-host -ForegroundColor Yellow (Measure-Command {
                    if($full){
                        $factu = [PSCustomObject]@{
                            Groups         = ($AdsiItem.memberOf -match '_FACT')
                            Attribut       = [PSCustomObject]@{
                                CAP             = $($AdsiItem.properties.extensionattribute6)
                                ASP             = $($AdsiItem.properties.extensionattribute7)
                            }
                        }
                    } else {
                        $factu = ''
                        if($AdsiItem.extensionattribute6){$factu += "Cap:$($AdsiItem.extensionattribute6)"}
                        if($AdsiItem.extensionattribute7){$factu += "Asp:$($AdsiItem.extensionattribute7)"}
                    }

                    # write-color $AdsiItem.samaccountname.padright(30),' ', "$($item.accountexpires)".padright(20),' ',$item.pwdlastset -fore cyan,yellow,red
                    
                    $PwdLastSet = [datetime]::FromFileTimeUtc($AdsiItem.ConvertLargeIntegerToInt64($AdsiItem.pwdlastset.value))
                    if($AdsiItem.extensionattribute14 -match '\d{18}@.+\\.+'){
                        ($lesspassTicks, $lesspassScope) = $AdsiItem.extensionattribute14 -split('@')
                        $LesspassDate = (get-date ([int64]$lesspassTicks)).ToUniversalTime()
                        if([Math]::Abs(($PwdLastSet - $LesspassDate).Totalseconds) -lt 120) {
                            $PassWordType = $lesspassScope
                        } else {
                            $PassWordType = $null
                        }
                    } else {
                        $PassWordType = $null
                    }
                    # write-color $AdsiItem.extensionattribute14, ' ',$PassWordType -fore cyan, red, Magenta, Yellow
                    if($Item.properties.accountexpires -and $Item.properties.accountexpires -lt 9223372036854775807){
                        $ExpireDate = [datetime]::fromfiletime([int64]$($Item.properties.accountexpires))
                    } else {
                        # 0 or 0x7FFFFFFFFFFFFFFF (9223372036854775807) indicates that the account never expires
                        $ExpireDate = $null
                    }
                    # write-color $AdsiItem.samaccountname.padright(30),' ',$ExpireDate, ' ',$Item.properties.accountexpires, ' ', $PassWordType -fore cyan, red, Magenta, Yellow

                # }).TotalSeconds
                [PSCustomObject]@{
                    NtAccountName        = $($AdsiItem.userPrincipalName) -replace ('(.+)@(.+)\..+', '$2\$1')
                    DisplayName          = "$($AdsiItem.name)"
                    Sid                  = "$sid"
                    email                = "$($AdsiItem.mail)" # + $($AdsiItem.proxyAddresses)"
                    Type                 = $TsAllowLogon
                    State                = $state
                    Phone                = "$($AdsiItem.telephonenumber)"
                    Description          = "$($AdsiItem.description)"
                    Facturation          = $factu
                    PasswordType         = $PassWordType
                    PasswordDate         = $PwdLastSet
                    ExpireDate           = $ExpireDate
                    Groupes              = $($AdsiItem.memberOf | ? {$_} | % {$_.split(',=')[1]}) # -join ("`n") # | ForEach-Object {([adsi]"LDAP://$_").name}
                    Externe              = $($AdsiItem.properties.extensionattribute6) -match 'EXT$' -or $($AdsiItem.properties.extensionattribute7) -match 'EXT$'
                }
            } catch {
                Write-LogStep -prefix "L.$($_.InvocationInfo.ScriptLineNumber)" '',$_ error
            }
        }
    }
    end {}
}
function Convert-AdsiUserToMail {
    <#
        .SYNOPSIS
            Converti des object ADSI et PSCustomObject
        .DESCRIPTION
            recupere les info de principale
        .PARAMETER Items
             
        .EXAMPLE
            Convert-AdsiUsers
        .NOTES
            Alban LOPEZ 2019
            alban.lopez@gmail.com
            http://git/PowerTech/
    #>

    [CmdletBinding()]
    param (
        [Parameter(ValueFromPipeline=$true)]$Items
    )
    begin {
    }
    process {
        foreach ($item in $items) {
            $AdsiItem = $item | ForEach-Object{[adsi]$_.path}
            if (($AdsiItem.userAccountControl.value -band 0x02)) {$state ='Disabled'} else {$state = ''}
            [PSCustomObject]@{
                NtAccountName        = $($AdsiItem.userPrincipalName) -replace ('(.+)@(.+)\..+', '$2\$1')
                DisplayName          = $($AdsiItem.name)
                email                = $($AdsiItem.mail) # + $($AdsiItem.proxyAddresses)"
                State                = $state
                ExtensionAttribute1  = $($AdsiItem.properties.extensionattribute1)
                # proxyaddresses = $($AdsiItem.properties.proxyaddresses)
                AllAddresses         = $($AdsiItem.properties.proxyaddresses -match '\w[A-Za-z0-9-_]+@[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+') -replace('.+:(.+@.+)','$1')
                msexchhomeservername = $($AdsiItem.properties.msexchhomeservername)
                msExchServerName     = $($AdsiItem.properties.msexchhomeservername -replace('.*/cn=(.+)$','$1'))
                msExchDbName         = $($AdsiItem.properties.homemdb -replace('^CN=(.|[^,]+),CN=.*','$1'))
                msExchQuotaGb        = $($Item.properties.msexchdumpsterquota) / 1Mb
                msExchDelegateBal    = $($AdsiItem.properties.msexchdelegatelistbl)
                msExchArchiveName    = $($AdsiItem.properties.msexcharchivename)
                msExchArchDbName     = $($AdsiItem.properties.msexcharchivedatabaselink -replace('^CN=(.|[^,]+),CN=.*','$1'))
                msExchArchPolicy     = $($AdsiItem.properties.msexchmailboxtemplatelink -replace('^CN=(.|[^,]+),CN=.*','$1'))
                msExchArchiveQuotaGb = $($Item.properties.msexcharchivequota) / 1Mb
            }
        }
    }
    end {}
}
function Convert-AdsiFactUsers {
    <#
        .SYNOPSIS
            Converti des object ADSI et PSCustomObject
        .DESCRIPTION
            recupere les info de factu
        .PARAMETER Items
             
        .EXAMPLE
            Convert-AdsiUsers
        .NOTES
            Alban LOPEZ 2019
            alban.lopez@gmail.com
            http://git/PowerTech/
    #>


    [CmdletBinding()]
    param (
        [Parameter(ValueFromPipeline=$true)]$Items
    )
    begin {
    }
    process {
        foreach ($item in $items) {
            # Write-Object $item -fore Magenta -backGroundColor Gray
            $AdsiItem = $item | ForEach-Object {[adsi]$_.path}
            # write-host -ForegroundColor Green (Measure-Command {
                try {
                    if($AdsiItem.InvokeGet("AllowLogon") -ne $false) {
                        $TsAllowLogon = $true
                    } else {
                        $TsAllowLogon = $false
                    }
                    # $TsAllowLogon = !($AdsiItem.InvokeGet("AllowLogon"))
                } catch {$TsAllowLogon = $true}
            # }).TotalSeconds
            # Write-Color '[',$item.invokeget('allowlogon'),' vs ',$AdsiItem.invokeget('allowlogon'),' vs ',$TsAllowLogon,']' -fore white,Magenta,Cyan,Yellow,Cyan,Green,white

            # write-host -ForegroundColor cyan (Measure-Command {
                try {
                    $sid = (New-Object Security.Principal.SecurityIdentifier( $AdsiItem.objectSid.Value, 0)).Value
                } catch {$sid = $null}
            # }).TotalSeconds
            [PSCustomObject]@{
                Sid            = $sid
                Enabled        = [bool](!($AdsiItem.userAccountControl.value -band 0x02))
                SamAccountName = $($AdsiItem.SamAccountName)
                NtAccountName  = $($AdsiItem.userPrincipalName) -replace ('(.+)@(.+)\..+', '$2\$1')
                email          = "$($AdsiItem.mail)" # + $($AdsiItem.proxyAddresses)"
                TsAllowLogon   = $TsAllowLogon
                Externe        = $($AdsiItem.properties.extensionattribute6) -match 'EXT$' -or $($AdsiItem.properties.extensionattribute7) -match 'EXT$'
                Facturation    = [PSCustomObject]@{
                    Groups         = ($AdsiItem.memberOf -match '_FACT')
                    Attribut       = [PSCustomObject]@{
                        CAP             = $($AdsiItem.properties.extensionattribute6)
                        ASP             = $($AdsiItem.properties.extensionattribute7)
                    }
                }
            }
        }
    }
    end {}
}
# Export-ModuleMember -Function Convert-RdSession, Get-RdSession
Write-LogStep 'Chargement du module ',$PSCommandPath ok