Question ADSI et variables

Plus d'informations
il y a 15 ans 7 mois #7495 par Thomas
ADSI et variables a été créé par Thomas
Bonjour a tous,

Un léger petite problème viens interrompre ma joie. Mon script s'appuie sur un fichier csv dont une colonne s'appelle groupe, OU, etc...

Je voudrais pour chaque utilisateur les insérer dans un groupe MAIS ma variable n'ai pas prise en compte!

Voici le bout de code concerné :

foreach ($user in $csvPath)
{


$gr=$user.groupe
$CN=$user.Name $userprincipalName = $user.userPrincipalName
$OU=$user.OU

#Ajout dans le/les groupes
$objGroupe[ADSI]'LDAP://CN=$gr,CN=Users,DC=ab,DC=COM'

$objGroupe.Add('LDAP://CN=$CN,OU=$OU,DC=ab,DC=COM')
$objGroupe.SetInfo()

}

Je fait pourtant un write-host $OU $CN et il me sort bien mes OU et Nom.

Merci pour votre aide.

Connexion ou Créer un compte pour participer à la conversation.

Plus d'informations
il y a 15 ans 7 mois #7497 par Richard Lazaro
Réponse de Richard Lazaro sur le sujet Re:ADSI et variables
Bonjour,

Ta variable $csvPAth contient le chemin vers le fichier à ce moment précis ?

Car si c'est le cas, c'est tout à fait normal que cela ne fonctionne pas.
Il faut que tu lises et transformes les données de ton csv en tableau d'objet avec la Cmdlet Import-Csv.

Si je comprends bien ton besoin :

[code:1]foreach($user in (Import-Csv -Path $csvPath -Delimiter ';')) {
$gr = $user.Groupe
$cn = $user.Name
$userPrincipalName = $user.UserPrincipalName
$ou = $user.Ou

#Ajout dans le/les groupes
$objGroupe[ADSI]'LDAP://CN=$gr,CN=Users,DC=ab,DC=COM'
$objGroupe.Add('LDAP://CN=$cn,OU=$ou,DC=ab,DC=COM')
$objGroupe.SetInfo()
}[/code:1]

Bien Cordialement,
Richard Lazaro.

Think-MS : (Get-Life).Days | %{ Learn-More }

\\"Problems cannot be solved by the same level of thinking that created them.\\" - Albert Einstein

Connexion ou Créer un compte pour participer à la conversation.

Plus d'informations
il y a 15 ans 7 mois #7510 par Thomas
Réponse de Thomas sur le sujet Re:ADSI et variables
Voici le code complet et l'erreur : (POWERSHELL V1)

#Début du script
$csvPath = Import-Csv 'utilisateurs.csv' #import du csv, séparation par des virgules car version 1 pour windows 2003, très

important !!


#Récupération du domaine courant sous la forme @test.com
$domaineSMTP=\"@$env:USERDNSDOMAIN\"


#Récupération du domaine courant sous la forme test.com
$domaineLDAP=$env:USERDNSDOMAIN

#Transformation de la chaine DNS en chaine de connexion LDAP
$domaineLDAP = $domaineLDAP.replace('.',',DC=')

#ajout de DC= en en-tête de chaine
$domaineLDAP=\"DC=$domaineLDAP\"


#Boucle foreach, on balai le fichier csv
foreach ($user in $csvPath)
{

#On ne met pas First Name Last Name ou les champs qui apparaissent sur l'interface graphique
#En ligne de commande elle porte un autre nom
#On fais correspondre chaque colone du csv a une variable (GivenName etc…) pour pouvoir les mettres au bon endroit lors de la

création

$OU1=$user.OU


$objOU=[ADSI]\"LDAP://OU=$OU1,$domaineLDAP\" #connexion a l'ad
#Attention pour le CN=USERS, c'est un container par défaut, ne pas confondre container par défaut et OU.
#Si c'est une OU, on met OU=MONOU




$CN= $user.Name #Canonical Name
$userprincipalName = $user.userPrincipalName #Nom d'ouverture de session
$givenName = $user.givenName #Correspond au prénom dans l'interface graphique
$SN = $user.Surname #Correspond au nom
$telephoneNumber = $user.telephoneNumber #Numéro de téléphone
$DisplayName = $user.DisplayName #Nom affiché
$samAccountName = $user.samAccountName


$gr=$user.groupe


$objUser = $objOU.Create( \"user\",\"CN=$CN\")
$objUser.put(\"samAccountName\",$samAccountName)
$objUser.put(\"userprincipalName\",$user.samAccountName + $domaineSMTP)

$objUser.put(\"givenName\",$givenName)
$objUser.put(\"sn\",$SN)
$objUser.put(\"telephoneNumber\",$telephoneNumber)
$objUser.put(\"DisplayName\",$DisplayName)
$objUser.SetInfo()
$Pwrd = $user.Password
$objUser.psbase.invoke(\"setPassword\",$Pwrd)
$objUser.psbase.invokeSet(\"AccountDisabled\",$False)
$objUser.psbase.CommitChanges()


#Ajout dans le/les groupes
$objGroupe=[ADSI]'LDAP://CN=$gr,CN=Users,$domaineLDAP'
$objGroupe.Add('LDAP://CN=$CN,OU=$OU1,$domaineLDAP')
$objGroupe.SetInfo()


#$objGroupe=[ADSI]'LDAP://CN=miam,CN=Users,DC=DOM01,DC=COM'
#$objGroupe.Add('LDAP://CN=Eponge Bob,OU=ordi,DC=DOM01,DC=COM')
#$objGroupe.SetInfo()


#Création de la home directory, le chemin doit etre specifié dans le fichier csv
new-item -path $($user.homeDirectory +'\'+ $CN) -type directory


write-host \"user\" $samAccountName \"créé avec succès!\"
write-host $groupe
write-host $CN
}



Quand ce fichier est exécuté, voici l'erreur :

Une syntaxe non valide DN a été spécifié .....par rapport a ma ligne LDAP ??<br><br>Message édité par: thomascap, à: 2/08/10 13:05

Connexion ou Créer un compte pour participer à la conversation.

Plus d'informations
il y a 15 ans 7 mois #7513 par Alan Pinard
Réponse de Alan Pinard sur le sujet Re:ADSI et variables
Bonjour,

Est-ce que tu pourrais nous poster un exemple de fichier CSV que tu utilise?

Merci,

Alan Pinard
Version A

Connexion ou Créer un compte pour participer à la conversation.

Plus d'informations
il y a 15 ans 7 mois #7514 par Thomas
Réponse de Thomas sur le sujet Re:ADSI et variables
voici un exemple de csv, découpé par des virgules à renommer en csv

Cordialement

La pièce jointe fichiercsv.txt est absente ou indisponible

<br><br>Message édité par: thomascap, à: 2/08/10 16:16
Pièces jointes :

Connexion ou Créer un compte pour participer à la conversation.

Plus d'informations
il y a 15 ans 7 mois #7522 par Alan Pinard
Réponse de Alan Pinard sur le sujet Re:ADSI et variables
Bonjour,

J'ai retravaillé le script. Je l'ai subdivisé en fonction. Il compte maintenant 4 fonctions:

1. Get-ADGroup:
Elle permet de récupérer les informations du groupe dans l'AD. Elle renvoie un objet PSObject. Les propriétés de l'object sont:

CN
DistinguishedName
GroupType
InstanceType
Member
Name
objectCategory
objectClass
objectGUID
objectSid
sAMAccountName
sAMAccountType
LastModification
CreationDate


2. Create-ADUser:
Créer l'utilisateur dans l'AD et créé le répertoire personnel de ce dernier.

3. Get-ADUser:
Elle permet de récupérer les informations de l'utilisateur dans l'AD. Elle renvoie un objet PSObject. Les propriétés de l'objet sont:

CN
DistinguishedName
sAMAccountName
Name
objectGUID
objectSid
LastModification
CreationDate


4. ADD-ADGroupMember:
Permet d'ajouter un membre (utilisateur) dans un groupe.

Je n'ai pas eu le temps de mettre de la validation. Il serait donc judicieux de le faire.
Voici le code:

[code:1]
#Début du script

Function Get-ADGroup {

PARAM (
$Group
)
Write-Host -ForegroundColor Cyan \&quot;************Get-ADGroup\&quot;
# Référence technet.microsoft.com/fr-fr/library/ff730967%28en-us%29.aspx
# SAM Account Type Translation
# SAM_GROUP_OBJECT 0x10000000 268435456
# SAM_NON_SECURITY_GROUP_OBJECT 0x10000001 268435457
# SAM_ALIAS_OBJECT 0x20000000 536870912
# SAM_NON_SECURITY_ALIAS_OBJECT 0x20000001 536870913
# SAM_USER_OBJECT 0x30000000 805306368
# SAM_NORMAL_USER_ACCOUNT 0x30000000 805306368
# SAM_MACHINE_ACCOUNT 0x30000001 805306369
# SAM_TRUST_ACCOUNT 0x30000002 805306370

# Intance Type
# msdn.microsoft.com/en-us/library/ms676204%28VS.85%29.aspx
# 1 The head of naming context
# 2 This replica is not instantiated
# 4 The object is writable on this directory
# 8 The naming context above this one on this directory is held
# 10 The naming context is in the process of being constructed for the first time via replication
# 20 The naming context is in the process of being removed from the local DSA

# Group Type
# -2147483646 Global Security Group
# -2147483644 Local Security Group
# -2147483643 BuiltIn Group
# -2147483640 Universal Security Group

# Filtre qui sera utilisé pour la recherche
$strFilter = \&quot;(&amp;(objectCategory=group)(name=\&quot; + $Group + \&quot;«»))\&quot;

# Creation d'une instance de classe System.DirectoryServices.DirectoryEntry
$objAD = New-Object System.DirectoryServices.DirectoryEntry

# Creation d'une instance de classe System.DirectoryServices.DirectorySearcher
$objSearcher = New-Object System.DirectoryServices.DirectorySearcher

$objSearcher.SearchRoot = $objAD #Conscrit la recherche dans le domaine voulu
$objSearcher.PageSize = 1000 #Pagination par 1000 resultat par page
$objSearcher.Filter = $strFilter #Filtre de recherche

$objGroup = $objSearcher.FindOne()

#Creation d'un objet PSObject contenant les propriétées de l'objet groupe.
$objVAGroup = New-Object -TypeName System.Management.Automation.PSObject

$objVAGroup | Add-Member NoteProperty CN ($objGroup.GetDirectoryEntry()).cn
$objVAGroup | Add-Member NoteProperty DistinguishedName ($objGroup.GetDirectoryEntry()).DistinguishedName
$objVAGroup | Add-Member NoteProperty GroupType ($objGroup.GetDirectoryEntry()).GroupType
$objVAGroup | Add-Member NoteProperty InstanceType ($objGroup.GetDirectoryEntry()).InstanceType
$objVAGroup | Add-Member NoteProperty Member ($objGroup.GetDirectoryEntry()).Member
$objVAGroup | Add-Member NoteProperty Name ($objGroup.GetDirectoryEntry()).name
# $objVAGroup | Add-Member NoteProperty nTSecurityDescriptor ($objGroup.GetDirectoryEntry()).nTSecurityDescriptor
$objVAGroup | Add-Member NoteProperty objectCategory ($objGroup.GetDirectoryEntry()).objectCategory
$objVAGroup | Add-Member NoteProperty objectClass ($objGroup.GetDirectoryEntry()).objectClass
$objVAGroup | Add-Member NoteProperty objectGUID ($objGroup.GetDirectoryEntry()).objectGUID
$objVAGroup | Add-Member NoteProperty objectSid ($objGroup.GetDirectoryEntry()).objectSid
$objVAGroup | Add-Member NoteProperty sAMAccountName ($objGroup.GetDirectoryEntry()).sAMAccountName
$objVAGroup | Add-Member NoteProperty sAMAccountType ($objGroup.GetDirectoryEntry()).sAMAccountType
# $objVAGroup | Add-Member NoteProperty uSNChanged ($objGroup.GetDirectoryEntry()).uSNChanged
# $objVAGroup | Add-Member NoteProperty uSNCreated ($objGroup.GetDirectoryEntry()).uSNCreated
$objVAGroup | Add-Member NoteProperty LastModification ($objGroup.GetDirectoryEntry()).whenChanged
$objVAGroup | Add-Member NoteProperty CreationDate ($objGroup.GetDirectoryEntry()).whenCreated

$objVAGroup
}
Function Get-ADUser {
PARAM(
$User
)
Write-Host -ForegroundColor Cyan \&quot;************Get-ADUser\&quot;
# Toutes les propriétés de l'objet user dans AD
# Name
# ConvertDNWithBinaryToString
# ConvertLargeIntegerToInt64
# accountExpires
# adminCount
# badPasswordTime
# badPwdCount
# cn
# codePage
# company
# countryCode
# description
# displayName
# distinguishedName
# dSCorePropagationData
# givenName
# homeMDB
# homeMTA
# instanceType
# lastLogoff
# lastLogon
# lastLogonTimestamp
# legacyExchangeDN
# logonCount
# mail
# mailNickname
# mDBUseDefaults
# memberOf
# mobile
# msExchALObjectVersion
# msExchHomeServerName
# msExchMailboxGuid
# msExchMailboxSecurityDescriptor
# msExchPoliciesExcluded
# msExchPoliciesIncluded
# msExchUserAccountControl
# name
# nTSecurityDescriptor
# objectCategory
# objectClass
# objectGUID
# objectSid
# primaryGroupID
# proxyAddresses
# pwdLastSet
# sAMAccountName
# sAMAccountType
# scriptPath
# showInAddressBook
# sn
# telephoneNumber
# textEncodedORAddress
# userAccountControl
# userPrincipalName
# uSNChanged
# uSNCreated
# whenChanged
# whenCreated

# Filtre qui sera utilisé pour la recherche
$strFilter = \&quot;(&amp;(objectCategory=user)(displayName=\&quot; + $User + \&quot;«»))\&quot;

# Creation d'une instance de classe System.DirectoryServices.DirectoryEntry
$objAD = New-Object System.DirectoryServices.DirectoryEntry

# Creation d'une instance de classe System.DirectoryServices.DirectorySearcher
$objSearcher = New-Object System.DirectoryServices.DirectorySearcher

$objSearcher.SearchRoot = $objAD #Conscrit la recherche dans le domaine voulu
$objSearcher.PageSize = 1000 #Pagination par 1000 resultat par page
$objSearcher.Filter = $strFilter #Filtre de recherche

$objUser = $objSearcher.FindOne()

$objVAUser = New-Object -TypeName System.Management.Automation.PSObject

$objVAUser | Add-Member NoteProperty CN ($objUser.GetDirectoryEntry()).cn
$objVAUser | Add-Member NoteProperty DistinguishedName ($objUser.GetDirectoryEntry()).DistinguishedName
$objVAUser | Add-Member NoteProperty sAMAccountName ($objUser.GetDirectoryEntry()).sAMAccountName
$objVAUser | Add-Member NoteProperty Name ($objUser.GetDirectoryEntry()).Name
$objVAUser | Add-Member NoteProperty objectGUID ($objUser.GetDirectoryEntry()).objectGUID
$objVAUser | Add-Member NoteProperty objectSid ($objUser.GetDirectoryEntry()).objectSid
$objVAUser | Add-Member NoteProperty LastModification ($objUser.GetDirectoryEntry()).whenChanged
$objVAUser | Add-Member NoteProperty CreationDate ($objUser.GetDirectoryEntry()).whenCreated

$objVAUser
}
Function ADD-ADGroupMember {
PARAM(
$UserDN,
$GroupDN
)
Write-Host -ForegroundColor Cyan \&quot;************ADD-ADGroupMember\&quot;
$LdapGrpStr = \&quot;LDAP://\&quot; + $GroupDN
$LdapUsrStr = \&quot;LDAP://\&quot; + $UserDN

$objGroup = [ADSI]\&quot;$LdapGrpStr\&quot;
$objGroup.Add(\&quot;$LdapUsrStr\&quot;«»)
$objGroup.SetInfo()

}
Function Create-ADUser {
PARAM(
$User
)
Write-Host -ForegroundColor Cyan \&quot;************Create-ADUser\&quot;
#Transformation de la chaine DNS en chaine de connexion LDAP
$domaineLDAP = (\&quot;DC=\&quot; + $ENV:USERDNSDOMAIN.Replace(\&quot;.\&quot;,\&quot;,DC=\&quot;«»))

$OU1 = $User.OU
$objOU = [ADSI]\&quot;LDAP://OU=$OU1,$domaineLDAP\&quot; #connexion a l'AD
#Attention pour le CN=USERS, c'est un container par défaut, ne pas confondre container par défaut et OU. Si c'est une OU, on met OU=MONOU

$CN = $User.Name

Write-Host -ForegroundColor Cyan \&quot;Creation de l'utilisateur -&gt; $CN\&quot;
Write-Host -ForegroundColor Cyan \&quot;Information sur l'utilisateur:\&quot;
$User
Write-Host -ForegroundColor Cyan \&quot;**************************************************\&quot;

$objUser = $objOU.Create( \&quot;user\&quot;,\&quot;CN=$CN\&quot;«»)
$objUser.put(\&quot;samAccountName\&quot;,($User.samAccountName))
$objUser.put(\&quot;userprincipalName\&quot;,($User.samAccountName + \&quot;@\&quot; + $domaineLDAP))

$objUser.put(\&quot;givenName\&quot;,($User.givenName))
$objUser.put(\&quot;sn\&quot;,($User.SurName))
$objUser.put(\&quot;telephoneNumber\&quot;,($User.telephoneNumber))
$objUser.put(\&quot;DisplayName\&quot;,($User.DisplayName))
$objUser.SetInfo()

$Pwrd = $User.Password
$objUser.psbase.invoke(\&quot;setPassword\&quot;,$Pwrd)
$objUser.psbase.invokeSet(\&quot;AccountDisabled\&quot;,$False)
$objUser.psbase.CommitChanges()

#Creation du repertoire personnel de l'utilisateur
New-Item -Path $($User.homeDirectory + \&quot;\\&quot; + $CN) -ItemType Directory
}

(Import-Csv \&quot;C:\Test.csv\&quot;«») | ForEach { #import du csv, séparation par des virgules car version 1 pour windows 2003, très important !!

Create-ADUser -User $_

#Recupération sous forme d'objet du groupe dans lequel on désire ajouter une membre.
$objectGroup = Get-ADGroup -Group $_.Groupe

#Recupération sous forme d'objet de l'utilisateur que l'on vient tout juste de créer.
$objectUser = Get-ADUser -User $_.DisplayName

#Ajout de l'utilisateur dans le groupe
ADD-ADGroupMember -UserDN $objectUser.DistinguishedName -GroupDN $objectGroup.DistinguishedName

}
#Fin du script
[/code:1]

En espérant que cela t'aidera!

La pièce jointe CreateADUser.ps1 est absente ou indisponible

<br><br>Message édité par: Versiona, à: 2/08/10 21:57

Alan Pinard
Version A
Pièces jointes :

Connexion ou Créer un compte pour participer à la conversation.

Temps de génération de la page : 0.049 secondes
Propulsé par Kunena