IdentifiantMot de passe
Loading...
Mot de passe oublié ?Je m'inscris ! (gratuit)
Navigation

Inscrivez-vous gratuitement
pour pouvoir participer, suivre les réponses en temps réel, voter pour les messages, poser vos propres questions et recevoir la newsletter

Scripts/Batch Discussion :

[CLOTURE] Export / Import "paramétrable" d'utilisateur AD DS [PowerShell]


Sujet :

Scripts/Batch

Vue hybride

Message précédent Message précédent   Message suivant Message suivant
  1. #1
    Candidat au Club
    Homme Profil pro
    Technicien réseaux et télécoms
    Inscrit en
    Janvier 2020
    Messages
    2
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 40
    Localisation : Belgique

    Informations professionnelles :
    Activité : Technicien réseaux et télécoms

    Informations forums :
    Inscription : Janvier 2020
    Messages : 2
    Par défaut [CLOTURE] Export / Import "paramétrable" d'utilisateur AD DS
    Bonjour à tous,
    Je suis nouveau dans une boite d'informatique, et je souhaite mettre en place un script PowerShell permettant l'export et l'import de manière paramètrables pour des utilisateurs Active Directory.

    Pour l'instant, j'ai le script suivant, qui coince sur l'import maintenant. Le message qu'il me renseigne est que les paramètres passés dans les attributs n'existe pas :

    Voici le script dans sa dernière version :
    Code POWERSHELL : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    ##################################
    ## Export - Import AD Users     ##
    ## Creator : RTH                ##
    ## Date : 02-01-2020            ##
    ## Last update : 08-01-2020     ##
    ##################################
     
    #######
    ## ask the user the action he want's to operate
    #######
     
    $csvFileName = "ad-export.csv"
    $delimiter = ';'
     
    do{
        Write-host "Welcome in AD Users Export / Import"
        Write-Host "What action do you wanna operate ?"
        Write-host "Export active Users using the selected fields : (1)"
        Write-Host "Import a list of Users based on a csv file : (2)"
        $action = Read-Host -Prompt "Your choice"
    }while ( !($action -eq "1") -and !($action -eq "2"))
     
    # Import active directory module for running AD cmdlets
    Import-Module activedirectory
     
    if( $action -eq "1"){
     
        $chosenParameters = New-Object System.Collections.Generic.List[string]
     
        ##  READ THE PARAMETER FILE for the export ##
        $parameterFile = "export-parameters.txt"
        if (!(Test-Path -Path (join-path $PSScriptRoot $parameterFile))){
            if(!(Test-Path -Path (join-path $PSScriptRoot "export-parameters-default.txt"))){
                Write-Host "Error file not found" -ForegroundColor Red
                Exit
            }
            Write-Host "Only Default file found !" -ForegroundColor Yellow
            $parameterFile = join-path $PSScriptRoot "export-parameters-default.txt"
        }
     
        ## Get elements in file
        ForEach($Parameter in (Get-Content -Path $parameterFile)){
            if( $Parameter.StartsWith("#") ){
                $chosenParameters.Add($Parameter.subString(1))
            }
        }
        ## List elements
        $param = ""
        foreach( $option in $chosenParameters){
            $param += $option+", "
        }
        if( $param.EndsWith(', ')){
            $param = $param.Substring(0, ($param.Length-2))
        }
        Write-Host "Param = $param"
        Get-ADUser -filter 'Enabled -eq $true' -property (foreach{$chosenParameters}) | Select-Object (foreach{$chosenParameters}) | Export-Csv -Path (Join-Path $PSScriptRoot $csvFileName) -Delimiter $delimiter -NoTypeInformation
    }
    elseif ($action -eq "2"){
     
        $chosenParameters = New-Object System.Collections.Generic.List[string]
        $generatedDN = $null
        $userFailed = New-Object System.Collections.ArrayList
        $userSuccess = New-Object System.Collections.ArrayList
        $userExist = New-Object System.Collections.ArrayList
     
     
        ##  READ THE PARAMETER FILE for the import ##
        $parameterFile = "export-parameters.txt"
        if (!(Test-Path -Path (join-path $PSScriptRoot $parameterFile))){
            if(!(Test-Path -Path (join-path $PSScriptRoot "export-parameters-default.txt"))){
                Write-Host "Error file not found" -ForegroundColor Red
                Exit
            }
            Write-Host "Only Default file found !" -ForegroundColor Yellow
            $parameterFile = join-path $PSScriptRoot "export-parameters-default.txt"
        }
        ## Get the selected elements from file
        ForEach($Parameter in (Get-Content -Path $parameterFile)){
            if( $Parameter.StartsWith("#") ){
                $chosenParameters.Add($Parameter.subString(1))
            }
        }
        $parameterTable = @{}
        for($i = 0 ; $i -lt $chosenParameters.Count ; $i++ ){
            $parameterTable.Add($chosenParameters[$i], $null)
        }
     
        #Store the data from ADUsers.csv in the $ADUsers variable
        $ADUsers = Import-csv (Join-Path $PSScriptRoot $csvFileName) -Delimiter $delimiter
     
        #Loop through each row containing user details in the CSV file 
        foreach ($User in $ADUsers)
        {
            $exist = $null
     
            ## Verify if the OU of the current User Exists
            #Write-Host "ParameterTable "$parameterTable.Contains("DistinguishedName")
            if( !$parameterTable.Contains("DistinguishedName")){
                Write-Host "OU Generation unavailable because the DistinguishedName field doesn't exist." -ForegroundColor Red
                Write-Host "Import aborted due to missing field." -ForegroundColor Red
                exit
            }
            $distinguishedName = $user.DistinguishedName
            if( !($distinguishedName -eq $null)){
                $splittedDN = $distinguishedName.Split(",")
                $splittedDN = $splittedDN[1..($splittedDN.Count)]
                $rebuildDN = $splittedDN -join ","
            }
            else{
                Write-Host "DistinguishedName value is NULL" -ForegroundColor Red
            }
            Write-Host "This is the generated DistinguishedName that's going to be used : "$rebuildDN
            $generatedDN = $rebuildDN
            try{
                $generatedDNExist = [adsi]::Exists("LDAP://$generatedDN")
            }
            catch{
                Write-Host "The specified Path for the path doesn't exist." -ForegroundColor Red
                Write-Host "The User [$User.DisplayName] is going to be created in the Default Users Group of the Domain"
                $generatedDN = Get-ADDomain | select UsersContainer
            }
     
            ## create the table containing all the infos from the User var
            ## Convert the User to HashTable
            $HashUser = @{}
            $User.PSObject.Properties | ForEach-Object{
                if( $_.value -ne $null -and $_.value -ne "" ){
                    $name = "'"+$_.name+"'"
                    $value = '"'+$_.value+'"'
                    $HashUser.Add($name, $value)
                }
            }
     
            #Check to see if the user already exists in AD
            write-host "HashTable :" ($HashUser |Out-String)
            $username = $HashUser["'SamAccountName'"]
     
            #$exist = Get-ADUser -Identity $username -Properties *
            $exist = [bool](Get-ADUser -Filter { SamAccountName -eq $username })
           	#if (Get-ADUser -Identity $username -Properties *) {
    		#If user does exist, give a warning
            if( $exist ){
    		    Write-Host "A user account with username $username already exist in Active Directory." -ForegroundColor Red
                $userExist.Add($username)
            }
        	else {
            #User does not exist then proceed to create the new user account
                try{
                    $HashUser.Remove("'SamAccountName'")
                    New-ADUser -Name $HashUser["'name'"] -OtherAttributes $HashUser
                    $userSuccess.Add($HashUser["'name'"])
                }
                catch{
                    Write-Host $_.Exception.Message
                    $userFailed.Add($HashUser["'name'"])
                }
            }
    	}
     
        Write-Host "Report of the export action"
        Write-Host "Successfully added Users " -ForegroundColor Green
        Write-Host $userSuccess
        Write-Host "Already existing Users" -ForegroundColor Yellow
        Write-Host $userExist
        Write-Host "Error on adding Users" -ForegroundColor Red
        Write-Host $userFailed
    }

    Je l'accorde, c'est encore un peu le bazard car je suis encore en phase de test du script en question. Une fois qu'il sera opérationnel, je "rangerai" un peu dedans et mettrai les commentaires où il se doit (et ferai une petite doc correspondante).
    Voici les sorties console que j'ai lors du lancement du script :
    Code CONSOLE : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    PS C:\Users\Administrator> C:\Users\Administrator\Desktop\bulk_users1.ps1
    Welcome in AD Users Export / Import
    What action do you wanna operate ?
    Export active Users using the selected fields : (1)
    Import a list of Users based on a csv file : (2)
    Your choice: 2
    Only Default file found !
    This is the generated DistinguishedName that's going to be used :  CN=Users,DC=test,DC=domain,DC=com
    HashTable : 
    Name                           Value                                                                                                                                    
    ----                           -----                                                                                                                                    
    'DistinguishedName'            "CN=Administrator,CN=Users,DC=test,DC=domain,DC=com"                                                                                  
    'Enabled'                      "True"                                                                                                                                   
    'Name'                         "Administrator"                                                                                                                          
    'CN'                           "Administrator"                                                                                                                          
    'CannotChangePassword'         "False"                                                                                                                                  
    'SamAccountName'               "Administrator"                                                                                                                          
    
    
    
    Hit Line breakpoint on 'C:\Users\Administrator\Desktop\bulk_users1.ps1:214'
    [DBG]: PS C:\Users\Administrator>> 
    Hit Line breakpoint on 'C:\Users\Administrator\Desktop\bulk_users1.ps1:220'
    [DBG]: PS C:\Users\Administrator>> 
    The specified directory service attribute or value does not exist
    Parameter name: 'CannotChangePassword'
    Hit Line breakpoint on 'C:\Users\Administrator\Desktop\bulk_users1.ps1:233'
    [DBG]: PS C:\Users\Administrator>> 
    0
    This is the generated DistinguishedName that's going to be used :  CN=Users,DC=test,DC=domain,DC=com
    HashTable : 
    Name                           Value                                                                                                                                    
    ----                           -----                                                                                                                                    
    'Name'                         "R T - test"                                                                                                                             
    'GivenName'                    "R"                                                                                                                                      
    'Enabled'                      "True"                                                                                                                                   
    'DistinguishedName'            "CN=R T - test,CN=Users,DC=test,DC=domain,DC=com"                                                                                     
    'DisplayName'                  "R T - test"                                                                                                                             
    'CannotChangePassword'         "False"                                                                                                                                  
    'CN'                           "R T - test"                                                                                                                             
    'SamAccountName'               "rt-test"                                                                                                                                
    'Surname'                      "T"                                                                                                                                      
    
    
    
    Hit Line breakpoint on 'C:\Users\Administrator\Desktop\bulk_users1.ps1:214'
    [DBG]: PS C:\Users\Administrator>> 
    Hit Line breakpoint on 'C:\Users\Administrator\Desktop\bulk_users1.ps1:220'
    [DBG]: PS C:\Users\Administrator>> 
    The specified directory service attribute or value does not exist
    Parameter name: 'CannotChangePassword'
    Hit Line breakpoint on 'C:\Users\Administrator\Desktop\bulk_users1.ps1:233'
    [DBG]: PS C:\Users\Administrator>> 
    1
    This is the generated DistinguishedName that's going to be used :  CN=Users,DC=test,DC=domain,DC=com
    HashTable : 
    Name                           Value                                                                                                                                    
    ----                           -----                                                                                                                                    
    'Name'                         "R T2 - test"                                                                                                                            
    'GivenName'                    "R"                                                                                                                                      
    'Enabled'                      "True"                                                                                                                                   
    'DistinguishedName'            "CN=R T2 - test,CN=Users,DC=test,DC=domain,DC=com"                                                                                    
    'DisplayName'                  "R T2 - test"                                                                                                                            
    'CannotChangePassword'         "False"                                                                                                                                  
    'CN'                           "R T2 - test"                                                                                                                            
    'SamAccountName'               "rt2-test"                                                                                                                               
    'Surname'                      "T"                                                                                                                                      
    
    
    
    Hit Line breakpoint on 'C:\Users\Administrator\Desktop\bulk_users1.ps1:214'
    [DBG]: PS C:\Users\Administrator>> 
    Hit Line breakpoint on 'C:\Users\Administrator\Desktop\bulk_users1.ps1:220'
    [DBG]: PS C:\Users\Administrator>> 
    The specified directory service attribute or value does not exist
    Parameter name: 'CannotChangePassword'
    Hit Line breakpoint on 'C:\Users\Administrator\Desktop\bulk_users1.ps1:233'
    [DBG]: PS C:\Users\Administrator>> 
    2
    Report of the export action
    Successfully added Users 
    
    Already existing Users
    
    Error on adding Users
    "Administrator" "R T - test" "R T2 - test"
    
    PS C:\Users\Administrator>

    Pourriez-vous me dire pourquoi il rouspette sur les attributs que je lui renseigne ? J'ai trouver sur la toile, plusieurs script, mais à chaque fois, il code les paramètres en dur dans la commande New-ADUser, ce que personnellement, je trouve complètement bête, car on perd toute généricité du code.

    [EDIT] je viens de trouver une information à priori importante dans le Get-Help New-ADUser qui dit ceci :
    DESCRIPTION
    The New-ADUser cmdlet creates a new Active Directory user. You can set commonly used user property values by using the cmdlet parameters.

    Property values that are not associated with cmdlet parameters can be set by using the OtherAttributes parameter. When using this parameter be sure to place
    single quotes around the attribute name as in the following example.

    Donc, j'ai la liste des paramètres suivantes :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    [-Name] <String> [-AccountExpirationDate <DateTime>] [-AccountNotDelegated <Boolean>] [-AccountPassword <SecureString>] 
        [-AllowReversiblePasswordEncryption <Boolean>] [-AuthenticationPolicy <ADAuthenticationPolicy>] [-AuthenticationPolicySilo <ADAuthenticationPolicySilo>] [-AuthType 
        {Negotiate | Basic}] [-CannotChangePassword <Boolean>] [-Certificates <X509Certificate[]>] [-ChangePasswordAtLogon <Boolean>] [-City <String>] [-Company <String>] 
        [-CompoundIdentitySupported <Boolean>] [-Country <String>] [-Credential <PSCredential>] [-Department <String>] [-Description <String>] [-DisplayName <String>] 
        [-Division <String>] [-EmailAddress <String>] [-EmployeeID <String>] [-EmployeeNumber <String>] [-Enabled <Boolean>] [-Fax <String>] [-GivenName <String>] 
        [-HomeDirectory <String>] [-HomeDrive <String>] [-HomePage <String>] [-HomePhone <String>] [-Initials <String>] [-Instance <ADUser>] [-KerberosEncryptionType {None 
        | DES | RC4 | AES128 | AES256}] [-LogonWorkstations <String>] [-Manager <ADUser>] [-MobilePhone <String>] [-Office <String>] [-OfficePhone <String>] [-Organization 
        <String>] [-OtherAttributes <Hashtable>] [-OtherName <String>] [-PassThru] [-PasswordNeverExpires <Boolean>] [-PasswordNotRequired <Boolean>] [-Path <String>] 
        [-POBox <String>] [-PostalCode <String>] [-PrincipalsAllowedToDelegateToAccount <ADPrincipal[]>] [-ProfilePath <String>] [-SamAccountName <String>] [-ScriptPath 
        <String>] [-Server <String>] [-ServicePrincipalNames <String[]>] [-SmartcardLogonRequired <Boolean>] [-State <String>] [-StreetAddress <String>] [-Surname 
        <String>] [-Title <String>] [-TrustedForDelegation <Boolean>] [-Type <String>] [-UserPrincipalName <String>] [-Confirm] [-WhatIf] [<CommonParameters>]
    et j'y retrouve bien, en paramètres, le CannotChangePassword, ce qui explique donc pourquoi je ne pourrais pas le passer par OtherAttributes, ou me trompe-je ??

    Mais maintenant, comment générer une commande New-ADUser de manière à disposer de paramètres générique en fonction des paramètres que l'utilisateur aura définit dans le fichier CSV / txt de sélection des paramètres pour l'export ?
    La liste des paramètres sélectionnable est basée sur le document txt suivant : export-parameters-default.txt
    Et comment être certain, en générant la commande, que le paramètre renseigné est un paramètre valide ?

    En vous remerciant pour les quelques pistes et informations qu'il vous sera possible de m'apporter à la compréhension de la situation, je vous souhaite à tous une superbe journée.

    Raph

  2. #2
    Expert confirmé

    Homme Profil pro
    Responsable déploiement (SCCM, InTune, GPO)
    Inscrit en
    Juillet 2014
    Messages
    3 218
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 46
    Localisation : France, Seine Saint Denis (Île de France)

    Informations professionnelles :
    Activité : Responsable déploiement (SCCM, InTune, GPO)
    Secteur : Transports

    Informations forums :
    Inscription : Juillet 2014
    Messages : 3 218
    Par défaut
    et j'y retrouve bien, en paramètres, le CannotChangePassword, ce qui explique donc pourquoi je ne pourrais pas le passer par OtherAttributes, ou me trompe-je ??
    Je suis d'accord avec toi.


    La liste des paramètres sélectionnable est basée sur le document txt suivant : Pièce jointe 529141
    Et comment être certain, en générant la commande, que le paramètre renseigné est un paramètre valide ?
    J'ai déjà eu ce problème pour générer la commande avec les paramètres, j'ai utiliser le "Splatting Parameters".
    Tu peux regarder en quoi ça consiste :
    https://docs.microsoft.com/en-us/pow...w=powershell-6
    http://duffney.io/Splatting-Paramete...ancedFunctions

    A toi de valider que les entrées que tu as pré-définit (liste des paramètres sélectionnable) dans le csv sont correctes et les transposer en "Paramètre" ou OtherAttributes correctement.

  3. #3
    Candidat au Club
    Homme Profil pro
    Technicien réseaux et télécoms
    Inscrit en
    Janvier 2020
    Messages
    2
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 40
    Localisation : Belgique

    Informations professionnelles :
    Activité : Technicien réseaux et télécoms

    Informations forums :
    Inscription : Janvier 2020
    Messages : 2
    Par défaut
    Bonjour,
    Tout d'abord merci pour la réponse, mais je coince à présent sur un autre message d'erreur, à savoir:

    The name provided is not a properly formed account name


    Voici à présent le code que j'utilise :
    Code POWERSHELL : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    203
    204
    205
    206
    207
    208
    209
    210
    211
    212
    213
    214
    215
    216
    217
    218
    219
    220
    221
    222
    223
    224
    225
    226
    227
    228
    229
    ##################################
    ## Export - Import AD Users     ##
    ## Creator : RTH                ##
    ## Date : 02-01-2020            ##
    ## Last update : 09-01-2020     ##
    ##################################
     
    #######
    ## ask the user the action he want's to operate
    #######
     
    $csvFileName = "ad-export.csv"
    $delimiter = ';'
     
    do{
        Write-host "Welcome in AD Users Export / Import"
        Write-Host "What action do you wanna operate ?"
        Write-host "Export active Users using the selected fields : (1)"
        Write-Host "Import a list of Users based on a csv file : (2)"
        $action = Read-Host -Prompt "Your choice"
    }while ( !($action -eq "1") -and !($action -eq "2"))
     
    # Import active directory module for running AD cmdlets
    Import-Module activedirectory
     
    if( $action -eq "1"){
     
        $chosenParameters = New-Object System.Collections.Generic.List[string]
     
        ##  READ THE PARAMETER FILE for the export ##
        $parameterFile = "export-parameters.txt"
        if (!(Test-Path -Path (join-path $PSScriptRoot $parameterFile))){
            if(!(Test-Path -Path (join-path $PSScriptRoot "export-parameters-default.txt"))){
                Write-Host "Error file not found" -ForegroundColor Red
                Exit
            }
            Write-Host "Only Default file found !" -ForegroundColor Yellow
            $parameterFile = join-path $PSScriptRoot "export-parameters-default.txt"
        }
     
        ## Get elements in file
        ForEach($Parameter in (Get-Content -Path $parameterFile)){
            if( $Parameter.StartsWith("#") ){
                $chosenParameters.Add($Parameter.subString(1))
            }
        }
        ## List elements
        $param = ""
        foreach( $option in $chosenParameters){
            $param += $option+", "
        }
        if( $param.EndsWith(', ')){
            $param = $param.Substring(0, ($param.Length-2))
        }
        Write-Host "Param = $param"
        Get-ADUser -filter 'Enabled -eq $true' -property (foreach{$chosenParameters}) | Select-Object (foreach{$chosenParameters}) | Export-Csv -Path (Join-Path $PSScriptRoot $csvFileName) -Delimiter $delimiter -NoTypeInformation
    }
    elseif ($action -eq "2"){
     
        $chosenParameters = New-Object System.Collections.Generic.List[string]
        $generatedDN = $null
        $userFailed = New-Object System.Collections.ArrayList
        $userSuccess = New-Object System.Collections.ArrayList
        $userExist = New-Object System.Collections.ArrayList
        $newADUserParameters = (Get-Command New-ADUser).Parameters
        $defaultPassword = $null
        $confirmPassword = $null
     
        ## Enter the DefaultPassword for the Users
        do{
            cls
            if( !$defaultPassword -eq $confirmPassword ){
                Write-Host "Passwords do not match !"-ForegroundColor Red
            }
            Write-Host "Please enter the default password that's going to be used for the import :"
            $defaultPassword= Read-Host -Prompt "Enter password :"
            $confirmPassword= Read-Host -Prompt "Enter password :"
        }while (!($defaultPassword -eq $confirmPassword))
     
        #Write-host ($newADUserParameters.Keys |Out-String)
     
        ##  READ THE PARAMETER FILE for the import ##
        $parameterFile = "export-parameters.txt"
        if (!(Test-Path -Path (join-path $PSScriptRoot $parameterFile))){
            if(!(Test-Path -Path (join-path $PSScriptRoot "export-parameters-default.txt"))){
                Write-Host "Error file not found" -ForegroundColor Red
                Exit
            }
            Write-Host "Only Default file found !" -ForegroundColor Yellow
            $parameterFile = join-path $PSScriptRoot "export-parameters-default.txt"
        }
        ## Get the selected elements from file
        ForEach($Parameter in (Get-Content -Path $parameterFile)){
            if( $Parameter.StartsWith("#") ){
                $chosenParameters.Add($Parameter.subString(1))
            }
        }
        $parameterTable = @{}
        for($i = 0 ; $i -lt $chosenParameters.Count ; $i++ ){
            $parameterTable.Add($chosenParameters[$i], $null)
        }
     
        #Store the data from ADUsers.csv in the $ADUsers variable
        $ADUsers = Import-csv (Join-Path $PSScriptRoot $csvFileName) -Delimiter $delimiter
     
        #Loop through each row containing user details in the CSV file 
        foreach ($User in $ADUsers)
        {
            $exist = $null
    <#        for($i = 0 ; $i -lt $parameterTable.Count; $i++){
            
                $parameterTable.Set_Item($property, $User.$property)
                write-host "Propriété : "$property
            }
            #>
     
            ## Verify if the OU of the current User Exists
            #Write-Host "ParameterTable "$parameterTable.Contains("DistinguishedName")
            if( !$parameterTable.Contains("DistinguishedName")){
                Write-Host "OU Generation unavailable because the DistinguishedName field doesn't exist." -ForegroundColor Red
                Write-Host "Import aborted due to missing field." -ForegroundColor Red
                exit
            }
            $distinguishedName = $user.DistinguishedName
            if( !($distinguishedName -eq $null)){
                $splittedDN = $distinguishedName.Split(",")
                $splittedDN = $splittedDN[1..($splittedDN.Count)]
                $rebuildDN = $splittedDN -join ","
            }
            else{
                Write-Host "DistinguishedName value is NULL" -ForegroundColor Red
            }
            $generatedDN = $rebuildDN
            try{
                $generatedDNExist = [adsi]::Exists("LDAP://$generatedDN")
            }
            catch{
                Write-Host "The specified Path for the path doesn't exist." -ForegroundColor Red
                Write-Host "The User [$User.DisplayName] is going to be created in the Default Users Group of the Domain"
                $generatedDN = Get-ADDomain | select UsersContainer
            }
     
            ## create the table containing all the infos from the User var
            ## Convert the User to HashTable
            $HashUser = @{}
            $User.PSObject.Properties | ForEach-Object{
                if( $_.value -ne $null -and $_.value -ne "" ){
                    $name = $_.name
                    $value = $_.value
                    $HashUser.Add($name, $value)
                }
            }
     
            #Check to see if the user already exists in AD
            write-host "HashTable :" ($HashUser |Out-String)
            $username = $HashUser["SamAccountName"]
     
            $exist = [bool](Get-ADUser -Filter { SamAccountName -eq $username })
           	#If user does exist, give a warning
            if( $exist ){
    		    Write-Host "A user account with username $username already exist in Active Directory." -ForegroundColor Red
                $userExist.Add($username)
            }
        	else {
            #User does not exist then proceed to create the new user account
                try{
                    $HashUser.Remove("SamAccountName")
                    #$HashUser.Remove("CannotChangePassword")
                    $stringParameter = '-AccountPassword (ConvertTo-SecureString "'+$defaultPassword+'" -AsPlainText -Force) '
                    $hashParameter = @{
                        Name = '"'+$HashUser["name"].Replace(' ', '')+'"'
                        AccountPassword = (ConvertTo-SecureString $defaultPassword -AsPlainText -Force)
                    }
                    $attributes = @{}
                    foreach($key in $HashUser.Keys){
                        #$cleanKey = $key.Substring(1,($key.Length-2)) #gets the value back without the single quotes
                        $inNewADUserParameters = $newADUserParameters.ContainsKey($Key) #looking for the key in the Parameter List of the New-ADUser Command
                        if( $inNewADUserParameters){ 
                            write-host "The value [$Key] is a Parameter of new-ADUser" -ForegroundColor green
                            if( $HashUser["$key"] -eq 'True'){
                                $stringParameter += "-$Key 1 "
                                $hashParameter.Add($key, 1)
                            }
                            elseif ( $HashUser["$key"] -eq 'False'){
                                $stringParameter += "-$Key 0 "
                                $hashParameter.Add($key, 0)
                            }
                            elseif( $key -eq "Name" ){
                            }
                            else{
                                $value = '"'+$HashUser[$key]+'"'
                                write-host "Value of $key : $value"
                                $stringParameter += "-$key $value "
                                $hashParameter.Add($key, $value)
                            }
                        }
                        else{
                            $value = $HashUser[$key]
                            $attributes.Add($key, $value)
                        }
                    }
     
                    write-host "Generated Parameter for the New-ADUser cmdlet : $stringParameter"
                    write-host "add String parameter"
                    #New-ADUser $stringParameter #-OtherAttributes $attributes
                    write-host "HashParameter :" ($HashParameter |Out-String)
                    New-ADUser $hashParameter
                    #New-ADUser <#-Name $HashUser["'name'"]#> $parameter -OtherAttributes $HashUser
     
                    $userSuccess.Add($HashUser["name"])
                }
                catch{
                    Write-Host $_.Exception.Message
                    $userFailed.Add($HashUser["name"])
                }
                finally{
                    Pause
                }
            }
    	}
     
        Write-Host "Report of the export action"
        Write-Host "Successfully added Users " -ForegroundColor Green
        Write-Host $userSuccess
        Write-Host "Already existing Users" -ForegroundColor Yellow
        Write-Host $userExist
        Write-Host "Error on adding Users" -ForegroundColor Red
        Write-Host $userFailed
    }

    Auparavant, j'avais des messages signalant que le user ne pouvait être ajouté car pas de mot de passe définit alors que la politique de sécurité AD ne l'autorisait pas, ... j'ai donc mis en place une petite saisie de mot de passe rapide avec confirmation. Et à présent, il me râle dessus car le paramètre Name ne serait pas correctement définit.
    J'ai utilisé l'option de splatting parameters, mais cela ne fonctionne pas non plus. J'avais également utilisé la génération d'une chaîne de caractères pour passer les paramètres en me disant que ce serait plus aisé, mais rien n'y fait
    Quelqu'un pourrait me dire pourquoi il me fait ce message d'erreur alors que le paramètre Name est bien sans espace et entouré de "

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    add String parameter
    HashParameter : 
    Name                           Value                                                                                                                                    
    ----                           -----                                                                                                                                    
    Enabled                        1                                                                                                                                        
    GivenName                      "Michael"                                                                                                                                
    Surname                        "H"                                                                                                                                      
    Name                           "MichaelH"                                                                                                                               
    AccountPassword                System.Security.SecureString                                                                                                             
    CannotChangePassword           0                                                                                                                                        
    DisplayName                    "Michael H"                                                                                                                              
    
    
    
    The name provided is not a properly formed account name
    0
    Press Enter to continue...
    [EDIT] Dès lors que je lance la commande :
    new-aduser -name "IlanP" -DisplayName "Ilan P" -CannotChangePassword 0 -Surname "P" -GivenName "Ilan" -Enabled 1 -AccountPassword (ConvertTo-SecureString Password123 -AsPlainText -Force)

    Il ajout bien l'utilisateur à l'AD.

    En vous remerciant pour toute l'aide et les astuces qu'il vous sera possible de m'apporter, je vous souhaite à tous une excellente journée.

    [EDIT2]

    Je viens, par pure hasard, de trouver le forum et le post suivant :
    https://serverfault.com/questions/83...latting-errors
    Et l'on m'a mis sur la piste du $($ pour l'ajout de variables dans les chaînes de caractères, et hop, tout fonctionne.
    Voici donc le script complet et opérationnel, mais pas encore "optimisé". Je vais m'y mettre dès à présent et le reposter une fois qu'il sera finalisé.
    Code POWERSHELL : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    203
    204
    205
    206
    207
    208
    209
    210
    211
    212
    213
    214
    215
    216
    217
    218
    219
    220
    221
    222
    223
    224
    225
    226
    227
    228
    229
    230
    231
    232
    233
    234
    235
    236
    237
    238
    239
    240
    ##################################
    ## Export - Import AD Users     ##
    ## Creator : RTH                ##
    ## Date : 02-01-2020            ##
    ## Last update : 09-01-2020     ##
    ##################################
     
    #######
    ## ask the user the action he want's to operate
    #######
     
    $csvFileName = "ad-export.csv"
    $delimiter = ';'
     
    do{
        Write-host "Welcome in AD Users Export / Import"
        Write-Host "What action do you wanna operate ?"
        Write-host "Export active Users using the selected fields : (1)"
        Write-Host "Import a list of Users based on a csv file : (2)"
        $action = Read-Host -Prompt "Your choice"
    }while ( !($action -eq "1") -and !($action -eq "2"))
     
    # Import active directory module for running AD cmdlets
    Import-Module activedirectory
     
    if( $action -eq "1"){
     
        $chosenParameters = New-Object System.Collections.Generic.List[string]
     
        ##  READ THE PARAMETER FILE for the export ##
        $parameterFile = "export-parameters.txt"
        if (!(Test-Path -Path (join-path $PSScriptRoot $parameterFile))){
            if(!(Test-Path -Path (join-path $PSScriptRoot "export-parameters-default.txt"))){
                Write-Host "Error file not found" -ForegroundColor Red
                Exit
            }
            Write-Host "Only Default file found !" -ForegroundColor Yellow
            $parameterFile = join-path $PSScriptRoot "export-parameters-default.txt"
        }
     
        ## Get elements in file
        ForEach($Parameter in (Get-Content -Path $parameterFile)){
            if( $Parameter.StartsWith("#") ){
                $chosenParameters.Add($Parameter.subString(1))
            }
        }
        ## List elements
        $param = ""
        foreach( $option in $chosenParameters){
            $param += $option+", "
        }
        if( $param.EndsWith(', ')){
            $param = $param.Substring(0, ($param.Length-2))
        }
        Write-Host "Param = $param"
        Get-ADUser -filter 'Enabled -eq $true' -property (foreach{$chosenParameters}) | Select-Object (foreach{$chosenParameters}) | Export-Csv -Path (Join-Path $PSScriptRoot $csvFileName) -Delimiter $delimiter -NoTypeInformation
    }
    elseif ($action -eq "2"){
     
        $chosenParameters = New-Object System.Collections.Generic.List[string]
        $generatedDN = $null
        $userFailed = New-Object System.Collections.ArrayList
        $userSuccess = New-Object System.Collections.ArrayList
        $userExist = New-Object System.Collections.ArrayList
        $newADUserParameters = (Get-Command New-ADUser).Parameters
        $defaultPassword = $null
        $confirmPassword = $null
     
        ## Enter the DefaultPassword for the Users
        do{
            cls
            if( !$defaultPassword -eq $confirmPassword ){
                Write-Host "Passwords do not match !"-ForegroundColor Red
            }
            Write-Host "Please enter the default password that's going to be used for the import :"
            $defaultPassword= Read-Host -Prompt "Enter password :"
            $confirmPassword= Read-Host -Prompt "Enter password :"
        }while (!($defaultPassword -eq $confirmPassword))
     
        #Write-host ($newADUserParameters.Keys |Out-String)
     
        ##  READ THE PARAMETER FILE for the import ##
        $parameterFile = "export-parameters.txt"
        if (!(Test-Path -Path (join-path $PSScriptRoot $parameterFile))){
            if(!(Test-Path -Path (join-path $PSScriptRoot "export-parameters-default.txt"))){
                Write-Host "Error file not found" -ForegroundColor Red
                Exit
            }
            Write-Host "Only Default file found !" -ForegroundColor Yellow
            $parameterFile = join-path $PSScriptRoot "export-parameters-default.txt"
        }
        ## Get the selected elements from file
        ForEach($Parameter in (Get-Content -Path $parameterFile)){
            if( $Parameter.StartsWith("#") ){
                $chosenParameters.Add($Parameter.subString(1))
            }
        }
        $parameterTable = @{}
        for($i = 0 ; $i -lt $chosenParameters.Count ; $i++ ){
            $parameterTable.Add($chosenParameters[$i], $null)
        }
     
        #Store the data from ADUsers.csv in the $ADUsers variable
        $ADUsers = Import-csv (Join-Path $PSScriptRoot $csvFileName) -Delimiter $delimiter
     
        #Loop through each row containing user details in the CSV file 
        foreach ($User in $ADUsers)
        {
            $exist = $null
    <#        for($i = 0 ; $i -lt $parameterTable.Count; $i++){
            
                $parameterTable.Set_Item($property, $User.$property)
                write-host "Propriété : "$property
            }
            #>
     
            write-host "User :" ($User | Out-String) -ForegroundColor Yellow
            ## Verify if the OU of the current User Exists
            #Write-Host "ParameterTable "$parameterTable.Contains("DistinguishedName")
            if( !($parameterTable.Contains("DistinguishedName"))){
                Write-Host "OU Generation unavailable because the DistinguishedName field doesn't exist." -ForegroundColor Red
                Write-Host "Import aborted due to missing field." -ForegroundColor Red
                exit
            }
           <# $distinguishedName = $user.DistinguishedName
            if( !($distinguishedName -eq $null)){
                $splittedDN = $distinguishedName.Split(",")
                $splittedDN = $splittedDN[1..($splittedDN.Count)]
                $rebuildDN = $splittedDN -join ","
            }
            else{
                Write-Host "DistinguishedName value is NULL" -ForegroundColor Red
            }
            $generatedDN = $rebuildDN
            try{
                $generatedDNExist = [adsi]::Exists("LDAP://$generatedDN")
            }
            catch{
                Write-Host "The specified Path for the path doesn't exist." -ForegroundColor Red
                Write-Host "The User [$User.DisplayName] is going to be created in the Default Users Group of the Domain"
                $generatedDN = $null
            }#>
     
            ## create the table containing all the infos from the User var
            ## Convert the User to HashTable
            $HashUser = @{}
            $User.PSObject.Properties | ForEach-Object{
                if( $_.value -ne $null -and $_.value -ne "" ){
                    $name = $_.name
                    $value = $_.value
                    $HashUser.Add($name, $value)
                }
            }
            $HashUser.remove("SamAccountName")
     
            #Check to see if the user already exists in AD
            write-host "HashUser :" ($HashUser |Out-String) -ForegroundColor Cyan
     
            $username = $HashUser["Name"]
     
            $exist = [bool](Get-ADUser -Filter { Name -eq $username })
           	#If user does exist, give a warning
            if( $exist ){
    		    Write-Host "A user account with Name [$username] already exist in Active Directory.  Skipping creation ..." -ForegroundColor Red
                $userExist.Add($username)
            }
        	else {
                #User does not exist then proceed to create the new user account
                try{
                    #$HashUser.Remove("SamAccountName")
                    #$HashUser.Remove("CannotChangePassword")
                    $stringParameter = '-AccountPassword (ConvertTo-SecureString "'+$defaultPassword+'" -AsPlainText -Force) '
                    $password = (ConvertTo-SecureString $defaultPassword -AsPlainText -Force)
                    $hashParameter = @{
                        Name = "$($HashUser["name"])"
                        AccountPassword = $password
     
                    }
                    #if( !($generatedDN -eq $null)){
                    #    $hashParameter.Add("Path", '"'+$generatedDN+'"')
                    #}
                    $hashAttributes = @{}
                    foreach($key in $HashUser.Keys){
                        #$cleanKey = $key.Substring(1,($key.Length-2)) #gets the value back without the single quotes
                        $inNewADUserParameters = $newADUserParameters.ContainsKey($Key) #looking for the key in the Parameter List of the New-ADUser Command
                        if( $inNewADUserParameters){ 
                            write-host "The value [$Key] is a Parameter of new-ADUser" -ForegroundColor green
                            if( $HashUser["$key"] -eq 'True'){
                                $stringParameter += "-$Key 1 "
                                $hashParameter.Add($key, 1)
                            }
                            elseif ( $HashUser["$key"] -eq 'False'){
                                $stringParameter += "-$Key 0 "
                                $hashParameter.Add($key, 0)
                            }
                            elseif( ($key -eq "Name")){
                                $value = $HashUser[$key]
                                Write-Host "Value of $key : $value" -ForegroundColor Cyan
                            }
                            else{
                                $value = '"'+$HashUser[$key]+'"'
                                write-host "Value of $key : $value"
                                $stringParameter += "-$key $value "
                                $hashParameter.Add($key, $value)
                            }
                        }
                        else{
                            $value = $HashUser[$key]
                            write-host "Value of $key : $value is set as Attribute"
                            $hashAttributes.Add($key, $value)
                        }
                    }
     
                    write-host "Generated Parameter for the New-ADUser cmdlet : $stringParameter"
                    #New-ADUser $stringParameter #-OtherAttributes $hashAttributes
                    write-host "HashParameter :" ($HashParameter |Out-String)
                    Pause
                    New-ADUser @hashParameter
     
                    $userSuccess.Add($HashUser["name"])
                }
                catch{
                    Write-Host $_.Exception.Message
                    Write-Host $_.Exception
                    $userFailed.Add($HashUser["name"])
                }
                finally{
                    Pause
                }
            }
    	}
     
        Write-Host "Report of the export action"
        Write-Host "Successfully added Users " -ForegroundColor Green
        Write-Host $userSuccess
        Write-Host "Already existing Users" -ForegroundColor Yellow
        Write-Host $userExist
        Write-Host "Error on adding Users" -ForegroundColor Red
        Write-Host $userFailed
    }
    Encore merci à tous pour vos pensées.
    Raph

  4. #4
    Expert confirmé

    Homme Profil pro
    Responsable déploiement (SCCM, InTune, GPO)
    Inscrit en
    Juillet 2014
    Messages
    3 218
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 46
    Localisation : France, Seine Saint Denis (Île de France)

    Informations professionnelles :
    Activité : Responsable déploiement (SCCM, InTune, GPO)
    Secteur : Transports

    Informations forums :
    Inscription : Juillet 2014
    Messages : 3 218
    Par défaut
    Ok super, je doit dire que j'ai un peu de mal à lire le script mais j'ai retrouver le principe de "Splatting Parameters" conseillé

+ Répondre à la discussion
Cette discussion est résolue.

Discussions similaires

  1. [XL-2010] l'utilisateur choisi sa plage a exporter/importer
    Par ledon94 dans le forum Macros et VBA Excel
    Réponses: 3
    Dernier message: 15/03/2018, 10h41
  2. Import/Export de certains paramètres EDI
    Par camboui dans le forum Visual Studio
    Réponses: 1
    Dernier message: 08/06/2010, 10h32
  3. [Export-import] Comment faire ?
    Par phil_ma dans le forum Eclipse Java
    Réponses: 4
    Dernier message: 06/02/2005, 18h15
  4. Export / Imports de Bases
    Par Guizz dans le forum MS SQL Server
    Réponses: 2
    Dernier message: 21/07/2003, 14h18
  5. Export/import des logins et pwd
    Par Colargole dans le forum MS SQL Server
    Réponses: 14
    Dernier message: 17/07/2003, 16h07

Partager

Partager
  • Envoyer la discussion sur Viadeo
  • Envoyer la discussion sur Twitter
  • Envoyer la discussion sur Google
  • Envoyer la discussion sur Facebook
  • Envoyer la discussion sur Digg
  • Envoyer la discussion sur Delicious
  • Envoyer la discussion sur MySpace
  • Envoyer la discussion sur Yahoo