Good morning, I am creating a Script to create and update my Office365 users but it is giving me the following error:
Error occurred while executing GetUsers Code: Request_UnsupportedQuery Message: Unsupported or invalid query filter clause specified for property 'userPrincipalName' of resource 'User'. RequestId: 39641b2a-8464-4fa1-950b-f6fec0294175 DateTimeStamp: Mon, 05 Sep 2022 06:59:23 GMT HttpStatusCode: BadRequest HttpStatusDescription: Bad Request HttpResponseStatus: Completed
The Array is not working to.
This is my code (I'm sorry for putting so much code but I can't identify the error.):
<#
Description => Create new users and update ALL data of existing users. Ups and downs.
#>
Param(
[Parameter(Mandatory=$true)]
[array] $Datos
)
<#Param(
[array] $Datos
)#>
#Datos = @()
# Get the credential from Automation
$credential = Get-AutomationPSCredential -Name 'powershell'
#$userName = $credential.UserName
#$securePassword = $credential.Password
$userName = "UserName"
$securePassword = ConvertTo-SecureString -String "Password" -Force
$psCredential = New-Object –TypeName System.Management.Automation.PSCredential –ArgumentList $userName, $securePassword
#$Session = New-PSSession –ConfigurationName Microsoft.Exchange -ConnectionUri https://outlook.office365.com/powershell-liveid -Credential $Credential -Authentication Basic -AllowRedirection
$Session = New-PSSession –ConfigurationName Microsoft.Exchange -ConnectionUri https://outlook.office365.com/powershell-liveid -Credential $psCredential -Authentication Basic -AllowRedirection
Import-PSSession -Session $Session -DisableNameChecking:$true -AllowClobber:$true | Out-Null
#Connect-ExchangeOnline -Credential $psCredentia
# Connect to Microsoft AzureAD & Teams
Connect-AzureAD -Credential $psCredential
Connect-MicrosoftTeams -Credential $psCredential
#Connect-AzureAD -Credential $userName $securePassword
#Connect-MicrosoftTeams -Credential $userName $securePassword
<# -----------------------------------------------------------------------------------------------------------------------#>
<# ---- INICIO DEL FOREACH ----#>
<# -----------------------------------------------------------------------------------------------------------------------#>
ForEach ($Linea in $Datos) {
# Get the Parameters >>> User,Pass,Estado,AzureAD,Nom,Aps,Email,Puesto,Departamento,Empresa,Dni,Pais,Movil,Matricula,Email_Pro,Emai_Padre,Email_Madre,Tutor,Curso_Escolar
$CharArray =$Linea.Split(",")
$User = $CharArray[0]
$Pass = $CharArray[1]
$Estado = $CharArray[2]
$AzureAD = $CharArray[3]
$Nom = $CharArray[4]
$Aps = $CharArray[5]
$Email = $CharArray[6]
$Puesto = $CharArray[7]
$Departamento = $CharArray[8]
$Empresa = $CharArray[9]
$Dni = $CharArray[10]
$Pais = $CharArray[11]
$Movil = $CharArray[12]
$Matricula = $CharArray[13]
$Email_Pro = $CharArray[14]
$Emai_Padre = $CharArray[15]
$Email_Madre = $CharArray[16]
$Tutor = $CharArray[17]
#$Curso_Escolar = $CharArray[18]
$DisplayName = -join($CharArray[4]," ",$CharArray[5])
$UserPrincipalName = $CharArray[6]
$Email_Tutor = -join($CharArray[17],"@example.es")
$UserID = Get-AzureADUser -Filter "userPrincipalName eq '$userPrincipalName'"| Select-Object ObjectId -ExpandProperty ObjectID
<# -----------------------------------------------------------------------------------------------------------------------#>
<# ---- Comprobar si Existe o no el usuario y que hacer con el en AzureAD ----#>
<# -----------------------------------------------------------------------------------------------------------------------#>
if($UserID){
$EstadoAD = Get-mailbox -identity $UserPrincipalName | Select-Object ObjectId -ExpandProperty CustomAttribute1 # ALTA
#$DepartamentoAD = Get-mailbox -identity $UserPrincipalName | Select-Object ObjectId -ExpandProperty CustomAttribute2 # Alumnos_1BX
$MatriculaAD = Get-mailbox -identity $UserPrincipalName | Select-Object ObjectId -ExpandProperty CustomAttribute3 # BX1BYG;BX1DAR;BX1EFI;BX1FIL;BX1FYQ;BX1CAS;BX1CAT;BX1ING;BX1MAT;BX1TUT;BX1VOL
#$PuestoAD = Get-mailbox -identity $UserPrincipalName | Select-Object ObjectId -ExpandProperty CustomAttribute4 # BX1B
#$Curso_EscolarAD = Get-mailbox -identity $UserPrincipalName | Select-Object ObjectId -ExpandProperty CustomAttribute5 # 2022-2023
#$Email_PropioAD = Get-mailbox -identity $UserPrincipalName | Select-Object ObjectId -ExpandProperty CustomAttribute6 #
#$Email_PadreAD = Get-mailbox -identity $UserPrincipalName | Select-Object ObjectId -ExpandProperty CustomAttribute7 #
#$Email_MadreAD = Get-mailbox -identity $UserPrincipalName | Select-Object ObjectId -ExpandProperty CustomAttribute8 #
#$UserID = Get-AzureADUser -Filter "Mail eq $Email"| Select-Object ObjectId -ExpandProperty ObjectID
if ($MatriculaAD -ne $Matricula){
# Si cambia la Matricula...
$Accion = "Actualizar"
}
else{
if ($Estado -ne $EstadoAD){
switch ($Estado){
"ALTA"{
$Accion = "Alta"
break
}
"BAJA"{
$Accion = "Baja"
break
}
}
}
else{
$Accion = "Existe"
}
}
}
else{
$User = $User.ToString()
if ($AzureAD -eq 'SI'){
$Accion = "Nuevo"
}
else{
$Accion = "Nada"
}
}
<# -----------------------------------------------------------------------------------------------------------------------#>
<# ---- Acciones sobre usuario : Nuevo/Alta/Baja/Actualizar/Nada ----#>
<# -----------------------------------------------------------------------------------------------------------------------#>
switch ($Accion ){
"Nuevo"{
Write-Output "Nuevo => $Accion - $User"
if($Estado -eq "ALTA") {
$PasswordProfile = New-Object -TypeName Microsoft.Open.AzureAD.Model.PasswordProfile
$PasswordProfile.Password = $Pass
New-AzureADUser -DisplayName $DisplayName -PasswordProfile $PasswordProfile -UserPrincipalName $userPrincipalName -AccountEnabled $true -GivenName $Nom -Surname $Aps -MailNickName $User -UsageLocation 'ES'
Set-AzureADUser -ObjectId $UserPrincipalName -JobTitle $Puesto -Department $Departamento -CompanyName $Empresa -PhysicalDeliveryOfficeName $Estado
Set-Mailbox $UserPrincipalName -CustomAttribute1 $Estado
Set-Mailbox $UserPrincipalName -CustomAttribute2 $Departamento
Set-Mailbox $UserPrincipalName -CustomAttribute3 $Matricula
Set-Mailbox $UserPrincipalName -CustomAttribute4 $Puesto
Set-Mailbox $UserPrincipalName -CustomAttribute5 "2022-2023" $Curso_Escolarolar
Set-Mailbox $UserPrincipalName -CustomAttribute6 $Email_Pro
Set-Mailbox $UserPrincipalName -CustomAttribute7 $Emai_Padre
Set-Mailbox $UserPrincipalName -CustomAttribute8 $Email_Madre
Set-Mailbox $UserPrincipalName -CustomAttribute9 "ENVIAR"
Set-Mailbox $UserPrincipalName -CustomAttribute10 $DisplayName
Set-Mailbox $UserPrincipalName -CustomAttribute11 $Email_Tutor
Set-Mailbox $UserPrincipalName -CustomAttribute12 $Pass
}
; break
}
"Actualizar"{
Write-Output "Actualizar => $Accion - $User"
Set-Mailbox $UserPrincipalName -CustomAttribute3 $Matricula
; break
}
"Alta"{
Write-Output "Actualizar => $Accion - $User"
$PasswordProfile = New-Object -TypeName Microsoft.Open.AzureAD.Model.PasswordProfile
$PasswordProfile.Password = $Pass
Set-AzureADUser -ObjectId $userPrincipalName -DisplayName $DisplayName -AccountEnabled $true -GivenName $Nom -Surname $Aps -UsageLocation 'ES'
Set-AzureADUserPassword -ObjectId $UserID -Password $PasswordProfile
Set-Mailbox $UserPrincipalName -CustomAttribute1 $Estado
Set-Mailbox $UserPrincipalName -CustomAttribute3 $Matricula
Set-Mailbox $UserPrincipalName -CustomAttribute6 $Email_Pro
Set-Mailbox $UserPrincipalName -CustomAttribute9 "ENVIAR"
Set-Mailbox $UserPrincipalName -CustomAttribute10 $DisplayName
Set-Mailbox $UserPrincipalName -CustomAttribute11 $Email_Tutor
Set-Mailbox $UserPrincipalName -CustomAttribute12 $Pass
; break
}
"Baja"{
Write-Output "Baja => $Accion - $User"
Set-AzureADUser -ObjectId $userPrincipalName -AccountEnabled $false
<#Set-Mailbox $UserPrincipalName -CustomAttribute1 $Estado#>
Set-Mailbox $UserPrincipalName -CustomAttribute1 "BAJA"
; break
}
"Existe"{
Write-Output "El usuario $Accion - $User => Estado actual: $Estado"
; break
}
"Nada"{
Write-Output "No hacer $Accion => $AzureAD crear en Azure AD => $User"
; break
}
}
<# -----------------------------------------------------------------------------------------------------------------------#>
<# ---- Profesores => Añadir y Quitar Teams ----#>
<# -----------------------------------------------------------------------------------------------------------------------#>
if ($Departamento -eq 'Empleados_Profesores'){
Write-Output "##########################################################"
ForEach ($MatAD in $MatArrayAD){
$Accion = '---'
$IdGrupo = "---"
if ($Matricula -match $MatAD){
$Accion = 'YA Matriculado'
}
else{
$IdGrupo = Get-AzureADGroup -Filter "Mail eq '[email protected]'"| Select-Object ObjectId -ExpandProperty ObjectID
if ($IdGrupo){
$Accion = 'Borrar'
Remove-AzureADGroupOwner -ObjectId $IdGrupo -OwnerId $UserID
Remove-AzureADGroupMember -ObjectId $IdGrupo -MemberId $UserID
}
}
Write-Output "$User $Accion en $MatAD => $IdGrupo"
}
Write-Output "----------------------------------------------------------"
ForEach ($Mat in $MatArray){
$Accion = '---'
$IdGrupo = "---"
if ($MatriculaAD -match $Mat){
$Accion = 'YA Matriculado'
}
else{
$IdGrupo = Get-AzureADGroup -Filter "Mail eq '[email protected]'"| Select-Object ObjectId -ExpandProperty ObjectID
if ($IdGrupo){
$Accion = 'Matricular'
Add-AzureADGroupOwner -ObjectId $IdGrupo -RefObjectId $UserID
}
}
Write-Output "$User $Accion en $Mat => $IdGrupo"
}
Write-Output "----------------------------------------------------------"
}
<# -----------------------------------------------------------------------------------------------------------------------#>
<# ---- FIN DEL FOREACH ----#>
<# -----------------------------------------------------------------------------------------------------------------------#>
}
# Disconnect from Microsoft Teams
Disconnect-MicrosoftTeams
Disconnect-AzureAD
The error seems to be that i need to doble quote '$userPrincipalName'. But it seem that the Array is not getting filled.
What @Toni said is not working for me, my array is still not working.
Update 6/9/2022
Changed this:
$UserID = Get-AzureADUser -Filter "userPrincipalName eq '$userPrincipalName'"| Select-Object ObjectId -ExpandProperty ObjectID
For this:
$UserID = Get-AzureADUser -Filter "userPrincipalName eq ''$userPrincipalName''"| Select-Object ObjectId -ExpandProperty ObjectID
The first error is solved, but my Array is still not working.
CodePudding user response:
ok, first as discussed you need to escape single quotes in the UPN, e.g.:
$userPrincipalName = $userPrinicpalName -replace "'","''"
then it looks like you are specifying the wrong attribute name and I also guess there is no need to expand, your code:
$UserID = Get-AzureADUser -Filter "userPrincipalName eq '$userPrincipalName'"| Select-Object ObjectId -ExpandProperty ObjectID
change to:
$UserID = (Get-AzureADUser -Filter "userPrincipalName eq '$userPrincipalName'").id
But be aware that the Variable $UserId contains only the Id, nothing else.
Check your code, you have the same issue several times, e.g.:
Get-AzureADGroup -Filter "Mail eq '[email protected]'"| Select-Object ObjectId -ExpandProperty ObjectID
I am using the microsoft.graph module not the AZmodule like you. But the attribute names should be the same. So the parameters are named ObjectId, userId and so on but the attribute on the object is simply called Id.
Ok that's quite a different thing that the array $Datos is empty. This is an input parameter for the script and does not get filled by the script. So your issue is not within this script, the problem is related to the call of the script and passing the array to the parameter Datos. This has nothing to do with the code posted here....