Question Script création user et aadd group on 365

Plus d'informations
il y a 1 an 3 mois #32929 par Guillaume LAVERNHE
Bonjour,

J'ai une problématique avec mon script.

Déja voici le script complet :

[CmdletBinding()]
Param(
    [Parameter(Position = 0, Mandatory = $false, HelpMessage = 'Specify the path of the CSV file')]
    [Alias('CSVFile')]
    [string]$FilePath="AzureADBulkUserCreation.csv",
    [Parameter(Position = 1, Mandatory = $false, HelpMessage = 'Specify Credentials')]
    [Alias('Cred')]
    [PSCredential]$Credential,
    #MFA Account for Azure AD Account
    [Parameter(Position = 2, Mandatory = $false, HelpMessage = 'Specify if account is MFA enabled')]
    [Alias('2FA')]
    [Switch]$MFA
    

)

Function Install-AzureAD {
    Set-PSRepository -Name PSGallery -Installation Trusted -Verbose:$false
    Install-Module -Name AzureAD -AllowClobber -Verbose:$false
    Install-Module ExchangeOnlineManagement
}


Try {
    $CSVData = @(Import-CSV -Path $FilePath -ErrorAction Stop)
    Write-Verbose "Successfully imported entries from $FilePath" -Verbose
    Write-Verbose "Total no. of entries in CSV are : $($CSVData.count)" -Verbose

Catch {
    Write-Verbose "Failed to read from the CSV file $FilePath Exiting!"
    Break
}
Try {
    Import-Module -Name AzureAD -ErrorAction Stop -Verbose:$false | Out-Null
}
Catch {
    Write-Verbose "Azure AD PowerShell Module not found..."
    Write-Verbose "Installing Azure AD PowerShell Module..."
    Install-AzureAD
    Install-Module -Name ExchangeOnlineManagement 

}

Try {
    Write-Verbose "Connecting to Azure AD..." -Verbose
    if ($MFA) {
        Connect-AzureAD -ErrorAction Stop | Out-Null
    }
    Else {
        Connect-AzureAD -Credential $Credential -ErrorAction Stop | Out-Null
    }
}
Catch {
    Write-Verbose "Cannot connect to Azure AD. Please check your credentials. Exiting!"
    Break
}

$CheckedDomains = @{}


Foreach ($Entry in $CSVData) {
    # Verify that mandatory properties are defined for password
    $DisplayName = $Entry.DisplayName
    $Password = $Entry.PasswordProfile
    $UserPrincipalName = $Entry.UserPrincipalName
    }

    # Les noms des clés de la hashtable sont des noms de paramètre d'un cmdlet
    $Parameters=@{
    AccountEnabled=$true
    GivenName=$Entry.GivenName 
    Surname=$Entry.Surname
    DisplayName=$Entry.DisplayName
    MailNickName=$Entry.MailNickName 
    UserPrincipalName=$Entry.UserPrincipalName
    City=$Entry.City 
    Country=$Entry.Country 
    Department=$Entry.Department 
    JobTitle=$Entry.JobTitle
    PhysicalDeliveryOfficeName=$Entry.PhysicalDeliveryOfficeName 
    UsageLocation=$Entry.UsageLocation 
    StreetAddress=$Entry.StreetAddress 
    PostalCode=$Entry.PostalCode 
    CompanyName=$Entry.CompanyName
}

#On ajoute les champs qui demandent une vérification de contenu
if ($Entry.TelephoneNumber -ne [string]::Empty)
{ $Parameters.Add('TelephoneNumber',$Entry.TelephoneNumber) }

if ($Entry.Mobile -ne [string]::Empty)
{ $Parameters.Add('Mobile',$Entry.Mobile) }
    If (!$DisplayName) {
        Write-Warning '$DisplayName is not provided. Continuing to the next record'
        Continue
    }

    If (!$UserPrincipalName) {
        Write-Warning '$UserPrincipalName is not provided. Continuing to the next record'
        Continue
    }

    If (!$Password) {
        $Password = Read-Host -Prompt "Enter desired Password" -AsSecureString
        $BSTR = [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($Password)
        $Password = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto($BSTR)
        $PasswordProfile = New-Object -TypeName Microsoft.Open.AzureAD.Model.PasswordProfile
        $PasswordProfile.Password = $Password
        $PasswordProfile.EnforceChangePasswordPolicy = 1
        $PasswordProfile.ForceChangePasswordNextLogin = 1
    }
    Else {
        $PasswordProfile = New-Object -TypeName Microsoft.Open.AzureAD.Model.PasswordProfile
        $PasswordProfile.Password = $Password
        $PasswordProfile.EnforceChangePasswordPolicy = 1
        $PasswordProfile.ForceChangePasswordNextLogin = 1
    }

    
    #See if the user exists.
    Try{
        $ADuser = Get-AzureADUser -Filter "userPrincipalName eq '$UserPrincipalName'"
        }
    Catch{}

    #If so then movea along, otherwise create the user.
    If ($ADuser)
    {
        Write-Verbose "$UserPrincipalName already exists. User will be added to group if specified."
    }
    Else
    {

        Try {    
            New-AzureADUser @Parameters `
            -PasswordProfile $PasswordProfile 
            }


         Catch {
            Write-Error "$DisplayName : Error occurred while creating Azure AD Account. $_"
            Continue
        
               }
     }
     

#Make sure the user exists now.
        Try{
            $ADuser = Get-AzureADUser -Filter "userPrincipalName eq '$UserPrincipalName'"
            }
        Catch{
            Write-Warning "$DisplayName : Newly created account could not be found.  Continuing to next user. $_"
            Continue
             }

        Write-Verbose "$DisplayName : AAD Account is created successfully!" -Verbose

Start-Sleep -Seconds 10

# Add the user to a group.
If ($Entry.GroupsNames) {
    # Split the group names string into an array
    $GroupNames = ($Entry.GroupsNames).Split(";")
    Write-Output $GroupNames

    # Loop through each group name
    Foreach ($GroupName in $GroupNames) {
        # Get the group object from Azure AD
        try {
            $AadGroup = Get-AzureADGroup -SearchString "$GroupName"
            if (!$AadGroup) {
                # Group was not found
                Write-Warning "Group '$GroupName' was not found in Azure AD. Skipping."
                continue
            }
        } catch {
            Write-Warning "An error occurred while retrieving group '$GroupName' from Azure AD. Error: $_"
            continue
        }

        # Add the user to the group
        try {
            Add-AzureADGroupMember -ObjectId $AadGroup.ObjectID -RefObjectId $ADuser.ObjectID
        } catch {
            Write-Warning "An error occurred while adding user '$DisplayName' to group '$GroupName'. Error: $_"
            continue
        }
    }
}
            
#The user that will get a license
$UserToLicense = Get-AzureADUser -ObjectId "$UserPrincipalName"

#Define the plans that will be enabled
$EnabledPlans = 'SPB'
#Get the LicenseSKU and create the Disabled ServicePlans object
$LicenseSku = Get-AzureADSubscribedSku | Where-Object {$_.SkuPartNumber -eq 'SPB'} 

#Create the AssignedLicense object with the License and DisabledPlans earlier created
$License = New-Object -TypeName Microsoft.Open.AzureAD.Model.AssignedLicense
$License.SkuId = $LicenseSku.SkuId
$License.DisabledPlans = $DisabledPlans.ServicePlanId
 
#Create the AssignedLicenses Object 
$AssignedLicenses = New-Object -TypeName Microsoft.Open.AzureAD.Model.AssignedLicenses
$AssignedLicenses.AddLicenses = $License
$AssignedLicenses.RemoveLicenses = @()

#Assign the license to the user
Set-AzureADUserLicense -ObjectId $UserToLicense.ObjectId -AssignedLicenses $AssignedLicenses


#add user to distrib group
Connect-ExchangeOnline -Credential $Credential

Start-Sleep -Seconds 100
        
    If ($Entry.DistribGroups) {
        $DistribGroups = ($Entry.DistribGroups).Split(";")

        Foreach ($DistribGroup in $DistribGroups) {

            if ($DistribGroup -eq "None") {

                Write-Output "None entry" 
                }
            else {

                  Add-DistributionGroupMember –Identity $DistribGroup -Member $UserPrincipalName
        }
    }
 }

#Add the user to Shared Mailboxs

    If ($Entry.SharedMails) {
        $SharedMails = ($Entry.SharedMails).Split(";")


        Foreach ($SharedMail in $SharedMails) {

            if ($SharedMail -eq "None") {

                Write-Output "None entry" 
                }
            else {

                Add-MailboxPermission –Identity $SharedMail -User $UserPrincipalName -AccessRights FullAccess

        
                Add-RecipientPermission $SharedMail -AccessRights SendAs -Trustee $UserPrincipalName -Confirm
            }
       }
 }



Ce message contient des informations confidentielles



Get-ChildItem -Path $src -Filter *.csv -Recurse | ForEach-Object {

    $nextName = Join-Path -Path $dest -ChildPath $_.name

    while(Test-Path -Path $nextName)
    {
       $nextName = Join-Path $dest ($_.BaseName + "_$num" + $_.Extension)    
       $num+=1   
    }

    $_ | Move-Item -Destination $nextName
}

La partie qui ne fonctionne pas (en partie) et celle de l'ajout au groupes : 

# Add the user to a group.
If ($Entry.GroupsNames) {
    # Split the group names string into an array
    $GroupNames = ($Entry.GroupsNames).Split(";")
    Write-Output $GroupNames

    # Loop through each group name
    Foreach ($GroupName in $GroupNames) {
        # Get the group object from Azure AD
        try {
            $AadGroup = Get-AzureADGroup -SearchString "$GroupName"
            if (!$AadGroup) {
                # Group was not found
                Write-Warning "Group '$GroupName' was not found in Azure AD. Skipping."
                continue
            }
        } catch {
            Write-Warning "An error occurred while retrieving group '$GroupName' from Azure AD. Error: $_"
            continue
        }

        # Add the user to the group
        try {
            Add-AzureADGroupMember -ObjectId $AadGroup.ObjectID -RefObjectId $ADuser.ObjectID
        } catch {
            Write-Warning "An error occurred while adding user '$DisplayName' to group '$GroupName'. Error: $_"
            continue
        }
    }
}

Du coup mon erreur est la suivante , erreur qui ce produit uniquement sur certain groupe et pas tout le temp......

An error occurred while adding user 'Username' to group 'Groupname'. Error: Impossible de convertir « System.Object[] » en type « System.String », requis par le paramètre « ObjectId ». La méthode spécifiée n'e
st pas prise en charge.

Du coup j'ai essayé d'ajouter ça :     .ToString()  ici :   Add-AzureADGroupMember -ObjectId $AadGroup.ObjectID.ToString() -RefObjectId $ADuser.ObjectID.ToString()

mais sans succes car du coup j'ai cette erreur :

AVERTISSEMENT : An error occurred while adding user 'userrname' to group 'GroupName'. Error: Error occurred while executing AddGroupMember 
Code: Request_BadRequest
Message: Invalid object identifier 'System.Object[]'.
RequestId: 5ee01c8c-78f9-4b7f-995e-64819d0d65e3
DateTimeStamp: Mon, 09 Jan 2023 09:58:11 GMT
HttpStatusCode: BadRequest
HttpStatusDescription: Bad Request
HttpResponseStatus: Completed

J'ai aussi essayé ça :

# Loop through each group name
    Foreach ($GroupName in $GroupNames) {
        # Get the group object from Azure AD
        try {
            # Retrieve the first group object that matches the specified filter
            $AadGroup = Get-AzureADGroup -Filter "DisplayName eq '$GroupName'" | Select-Object -First 1
            if (!$AadGroup) {
                # Group was not found
                Write-Warning "Group '$GroupName' was not found in Azure AD. Skipping."
                continue
            }

pareil sans succes.......

Si quelqun a une idée je suis preneur 

Merci d'avance

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

Plus d'informations
il y a 1 an 3 mois #32930 par Laurent Dardenne
Salut,
vérifie si l'appel suivant :
 $AadGroup = Get-AzureADGroup -SearchString "$GroupName"
renvoie un ou plusieurs éléments :
Write-Warning "type =$($AadGroup.GetType())  count=$($AadGroup.Count)"
Tu peux aussi utiliser Export-clixml pour analyser son contenu, sinon un avec un .debugger.

Tutoriels PowerShell

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

Plus d'informations
il y a 1 an 3 mois #32932 par Guillaume LAVERNHE
Hello 

Merci poura ta réponse : 

voici ce que la commande renvoie :

AVERTISSEMENT : type =Microsoft.Open.AzureAD.Model.Group  count=1
AVERTISSEMENT : type =Microsoft.Open.AzureAD.Model.Group  count=1
AVERTISSEMENT : type =Microsoft.Open.AzureAD.Model.Group  count=1
AVERTISSEMENT : type =System.Object[]  count=2
AVERTISSEMENT : An error occurred while adding user '
Ce message contient des informations confidentielles
' to group '
Ce message contient des informations confidentielles
'. Error: Impossible de convertir « System.Object[] » en type « System.String », requis par le paramètre « ObjectId ». La 
méthode spécifiée n'est pas prise en charge.

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

Plus d'informations
il y a 1 an 3 mois #32933 par Laurent Dardenne
Ton appel à :
$AadGroup = Get-AzureADGroup -SearchString "$GroupName"
renvoi deux items pour un nom de groupe, il se peut que le cmdlet renvoie deux groupes ou un groupe et un autre objet dans le pipeline.
Dans ces cas là, où l'on s'attend à récupérer un seul objet au lieu d'un tableau, il est nécessaire d'analyser les données.L'usage d'Export-Clixml peut être utile, car il évite d'ajouter de nombreuses lignes de debug.

Peut être également vérifier la transformation de "$GroupName"...

Tutoriels PowerShell

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

Plus d'informations
il y a 1 an 3 mois #32934 par Guillaume LAVERNHE
Re,

Du coup j'ai résolu mon problème , 
 $AadGroup = Get-AzureADGroup -SearchString "$GroupName"
, mon bug était principalement sur un groupe  : exemple : Mon groupe ce nomme Groupe - ALL mais il y avait aussi un groupe nommer Groupe - ALL - West , du coup le -SearchString voyait 2 Groupes, 

J'ai remplace la ligne de code par : 
$AadGroup = Get-AzureADGroup -Filter "DisplayName eq '$GroupName'"
 

et maintenant tout est OK
 

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

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