azure active directory
137 TopicsGet a list of specific agegroup users stored on a security group
Dear Community, I wonder if it would be possible to get a list of users (stored in a security group) marked as "minor" and "not adult" using microsoft graph. Once I get the members of the group (using Get-MgGroupMember -GroupId XXXX), I am not sure how to retrieve only the ones with a specific agegroup property. Is that feasible? Any help would be greatly appreciated. Many thanks in advance!Solved42Views0likes2CommentsBulk update Azure AD with user attributes from CSV
I am looking for a way to update user attributes (OfficePhone and Department) for about 500 users from a CSV to AzureAD using a powershell. Does anyone know of a script that I could use? I am new here and if I have not given enough information, please let me know. I tried using Set-AzureADUser piping records using a foreach statement from a csv that I imported, but it was throwing up errors. Thanks! JacobSolved196KViews4likes71CommentsAdding External Users in-bulk to: Microsoft Teams & Private Channel(s) within the Team
We have a customer who requires over 350 external users (their customers) to be added / invited into a Team which has been created. "Half" of the users need to be added into "private channel a", and the other "Half" need to be added into "private channel b". We have attempted to add the users via various PowerShell scripts, however none of these scripts that we have been provided with have worked for various reasons. I have been unable to locate any native methods for this within the MS 365 admin centre, therefore believe that the only way to achieve this is by PowerShell scripting. Example of the most recent script we have is as follows, omitting the creation of the private channel(s) as they have already been created - see below: We require assistance with the actual script itself to: Add users into the team from a CSV of their email addresses. Assign the users to the correct private channel. Note - users will be added in 2 batches - 1 per private channel, so we just require scripting that can be modified to achieve this. # Install the Microsoft Teams PowerShell Module Install-Module -Name PowerShellGet -Force -AllowClobber Install-Module -Name MicrosoftTeams -Force -AllowClobber # Connect to Microsoft Teams Connect-MicrosoftTeams # Define the team name and path to the CSV file $teamName = "Your Team Name" $csvPath = "C:\path\to\your\users.csv" # Get the GroupId of the team $team = Get-Team -DisplayName $teamName $groupId = $team.GroupId # Import users from the CSV file $users = Import-Csv $csvPath # Add external users to the team foreach ($user in $users) { Add-TeamUser -GroupId $groupId -User $user.Email } # Define the private channel name $privateChannelName = "Private Channel Name" # Create the private channel New-TeamChannel -GroupId $groupId -DisplayName $privateChannelName -MembershipType Private # Get the ChannelId of the private channel $channel = Get-TeamChannel -GroupId $groupId -DisplayName $privateChannelName $channelId = $channel.Id # Add users to the private channel foreach ($user in $users) { Add-TeamChannelUser -GroupId $groupId -User $user.Email -ChannelId $channelId }44Views0likes0CommentsMicrosoft Graph Sign in Log Script
Hi all, I'm trying to create a script that will check sign ins based on the location. How ever the location always appears as 'Microsoft.Graph.PowerShell.Models.MicrosoftGraphSignInLocation'. I am able to see the location if I select the property 'location' by itself and expand the property, but then that only show's a list of the locations. If I add other properties, it either doesn't work or it displays like this: I tried exporting as a csv and the location column values showed up as 'Microsoft.Graph.PowerShell.Models.MicrosoftGraphSignInLocation'. This is what I have currently: Get-MgAuditLogSignIn -Filter "location/countryOrRegion eq 'AU'" -Top 10 | format-list And if I try selecting properties (I would add more properties later, this is just an example: $properties = 'location, userprincipalname' Get-MgAuditLogSignIn -All -Filter "location/countryOrRegion eq 'AU'" -Top 10 -Property $properties | Select -ExpandProperty $properties Has anyone tried something similar?Solved107Views1like3CommentsAssistance Needed with OneDrive and Office 365 Activity PowerShell Scripts
Dear All, I am using the scripts below to retrieve OneDrive and Office 365 activity details for my tenant. However, in the "User Principal Name" field, I am getting an ID instead of the email address. This issue started after September 18; prior to that, it was working fine and showing the email addresses as expected. I run these scripts daily and generate a Power BI report based on the output. Scripts Used Get User OneDrive Activity: Invoke-GraphApiRequest -uri "https://graph.microsoft.com/v1.0/reports/getOneDriveActivityUserDetail(date=$yesterdaydate)" -FileName "OneDrive\ODUserDailyActivity\OneDriveUserDailyActivity" -Verbose:$VerbosePreference Invoke-GraphApiRequest -uri "https://graph.microsoft.com/v1.0/reports/getOneDriveUsageAccountDetail(date=$yesterdaydate)" -FileName "OneDrive\ODUsageDailyReport\OneDriveUsageDailyReport" -Verbose:$VerbosePreference Here is an example of the output Iām receiving: Report Refresh Date,User Principal Name,Is Deleted,Deleted Date,Last Activity Date,Viewed Or Edited File Count,Synced File Count,Shared Internally File Count,Shared Externally File Count,Assigned Products,Report Period 2024-11-22,830E1CDE8B16F21C80B207D213852737,False,,2024-11-22,1,0,0,0,MICROSOFT COPILOT STUDIO VIRAL TRIAL+MICROSOFT 365 E5+MICROSOFT COPILOT STUDIO USER LICENSE+MICROSOFT POWER AUTOMATE FREE+MICROSOFT INTUNE SUITE+MICROSOFT FABRIC (FREE)+MICROSOFT DEFENDER VULNERABILITY MANAGEMENT ADD-ON+DYNAMICS 365 CUSTOMER VOICE TRIAL+PLANNER AND PROJECT PLAN 3+POWER APPS PREMIUM+MICROSOFT POWER APPS FOR DEVELOPER,1 This is just one example, but I am seeing similar results for most of these scripts. Could you please help me resolve this issue? Thank you in advance!354Views0likes0CommentsExport Enterprise apps and signin count
I need to export all the configured enterprise apps and login count for each. This script does the job, but it truncates the application name (see example screen shot) and I can't figure out how to export the results to csv. Can anyone help? #To enable verbose [CmdletBinding()] Param() #Retrieve list of applications $Apps = Get-AzureADApplication #Loop through each application ForEach($App in $Apps){ Write-Verbose "Processing $($App.DisplayName)" #Retrieve logs filtered on AppID $Log = Get-AzureADAuditSignInLogs -All $true -filter "appid eq '$($App.AppID)'" #Create a custom object for output [PSCustomObject]@{ ApplicationName = $App.DisplayName ApplicationID = $App.AppID SignIns = $Log.count } #To prevent throttling on Sign-in Log querying, insert a sleep Start-Sleep 1 }258Views0likes3CommentsNew external/local user in B2C tenant
Hello, I'm trying to use Microsoft Graph API in PowerShell to create external/local users in our B2C tenant, but I receive the following error: "The domain portion of the userPrincipalName property is invalid. You must use one of the verified domain names in your organization." There must be a parameter to switch from an internal or federated user to an external one, but I've been unable to find it. Any help you can offer would be appreciated! Here is my script: $NewUsers = Import-Csv $NewCSVPath ForEach($NewUser in $NewUsers){ $TestTheUser = $null $TestTheUser = (Get-MGUser -UserId $NewUser.UserPrincipalName -ErrorAction SilentlyContinue).Id IF ($TestTheUser) { Continue } else { $PasswordProfile = @{ Password = "Ninja%67#Dangerous" ForceChangePasswordNextSignIn = $false } $UserParams = @{ DisplayName = $NewUser.DisplayName UserPrincipalName = $NewUser.UserPrincipalName PasswordProfile = $PasswordProfile AccountEnabled = $true MailNickname = $NewUser.MailNickname identities = @( @{ signInType = "emailAddress" issuer = "<MyTenant>.onmicrosoft.com" issuerAssignedId = $NewUser.UserPrincipalName } ) passwordPolicies = "DisablePasswordExpiration" } New-MgUser @UserParams } }302Views0likes3CommentsBulk Disable Azure AD Users
I am looking for a way to disable (not delete) 300 AzureAD users with the "AccountEnabled" field. I was able to find the script below from an older post but I keep getting an error. I'm new here and even newer to using Azure (& Powershell as a whole) so not sure what I am missing exactly. Any and all help would be greatly appreciated! Thanks in advance šš½ $CSVrecords = Import-Csv C:\Users\Downloads\Test.csv # Create arrays for skipped and failed users $SkippedUsers = @() $FailedUsers = @() # Loop trough CSV records foreach ($CSVrecord in $CSVrecords) { $upn = $CSVrecord.UserPrincipalName $user = Get-AzureADUser -Filter "UserPrincipalName eq '$upn'" if ($user) { try{ $user | Set-AzureADUser -AccountEnabled $CSVrecord.AccountEnabled } catch { $FailedUsers += $upn Write-Warning "$upn user found, but FAILED to deactivate." } } else { Write-Warning "$upn not found, skipped" $SkippedUsers += $upn } } The error I keep getting is "$upn user found, but FAILED to deactivate." My CSVs have two fields, UserPrincipalName & AccountEnabled I've even tried just swapping the line below of the one under that, but still get the same error. SWAPPED THIS: $user | Set-AzureADUser -AccountEnabled $CSVrecord.AccountEnabled FOR THIS: $user | Update-AzureADUser -AccountEnabled false Original code from Manfred101Solved25KViews0likes3CommentsFacing error when running a ps script using mggraph
Hi Community, I am facing issue in fetching lastsignindate from azure ad using mggraph it returns error of 404 not found whereas user is present in azure ad. The script i am sharing has some fields blank for security reasons: # Function to authenticate with Microsoft Graph function Get-GraphToken { param ( [string]$tenantId, [string]$clientId, [string]$clientSecret, [string]$authUrl ) $authBody = @{ grant_type = "client_credentials" scope = "https://graph.microsoft.com/.default" client_id = $clientId client_secret = $clientSecret } try { $tokenResponse = Invoke-RestMethod -Method Post -Uri $authUrl -ContentType "application/x-www-form-urlencoded" -Body $authBody return $tokenResponse.access_token } catch { Write-Error "Failed to authenticate with Microsoft Graph: $_" return $null } } # Function to get the most recent LastLogon attribute from all domain controllers function Get-LastLogon { param ( [string]$userName ) $dcs = Get-ADDomainController -Filter * | Select-Object -ExpandProperty HostName $lastLogon = 0 foreach ($dc in $dcs) { try { $user = Get-ADUser $userName -Server $dc -Properties LastLogon if ($user.LastLogon -gt $lastLogon) { $lastLogon = $user.LastLogon } } catch { Write-Error "Failed to retrieve LastLogon from $dc for $userName $_" } } if ($lastLogon -ne 0) { return [DateTime]::FromFileTime($lastLogon) } else { return $null } } # Function to get last sign-in date from Azure AD using User ID function Get-UserLastSignIn { param ( [string]$userId, [hashtable]$headers ) try { # Get the user's sign-in activity using userId $userInfo = Invoke-RestMethod -Uri "https://graph.microsoft.com/v1.0/users/$userId?$select=signInActivity" -Headers $headers if ($userInfo.signInActivity -and $userInfo.signInActivity.lastSignInDateTime) { # Return the lastSignInDateTime return [DateTime]::Parse($userInfo.signInActivity.lastSignInDateTime) } else { Write-Warning "No sign-in activity available for user with ID $userId." return $null } } catch { Write-Error "Failed to retrieve sign-in data for user with ID $userId $_" return $null } } # Function to send notification function Send-Notification { param ( [string]$userEmail, [string]$managerEmail ) $subject = "Login Reminder" $body = "You have not logged in for the past 10 days. Please log in to avoid account deactivation." # Uncomment the below line to send the actual email # Send-MailMessage -From "" -To $userEmail -Cc $managerEmail -Subject $subject -Body $body -SmtpServer $smtpServer } # Function to create and send the HTML report function Create-And-Send-HTMLReport { param ( [array]$csvData, [string]$htmlReportPath ) $htmlContent = @" <html> <head> <title>User Login Report</title> <style> table { width: 100%; border-collapse: collapse; } table, th, td { border: 1px solid black; } th, td { padding: 8px; text-align: left; } </style> </head> <body> <h2>User Login Report</h2> <table> <tr> <th>samAccountName</th> <th>DisplayName</th> <th>MailSentToManager</th> <th>LastLogonOnPrem</th> <th>LastLogonAzureAD</th> <th>SessionRevoked</th> <th>Action</th> </tr> "@ foreach ($row in $csvData) { $htmlContent += "<tr>" $htmlContent += "<td>$($row.samAccountName)</td>" $htmlContent += "<td>$($row.DisplayName)</td>" $htmlContent += "<td>$($row.MailSentToManager)</td>" $htmlContent += "<td>$($row.LastLogonOnPrem)</td>" $htmlContent += "<td>$($row.LastLogonAzureAD)</td>" $htmlContent += "<td>$($row.SessionRevoked)</td>" $htmlContent += "<td>$($row.Action)</td>" $htmlContent += "</tr>" } $htmlContent += @" </table> </body> </html> "@ # Save the HTML content to a file $htmlContent | Out-File -FilePath $htmlReportPath -Encoding UTF8 # Uncomment the below line to send the actual email # Send-MailMessage -From "" -To "" -Subject "Daily User Login HTML Report" -BodyAsHtml -Body $htmlContent -SmtpServer $smtpServer } # Function to send daily report to IT function Send-DailyReport { param ( [string]$reportPath ) $subject = "Daily User Login Report" $body = Get-Content -Path $reportPath -Raw # Uncomment the below line to send the actual email # Send-MailMessage -From "" -To "" -Subject $subject -Body $body -BodyAsHtml -SmtpServer $smtpServer -Port $smtpPort } # Main script starts here # Define variables $tenantId = "" $clientSecret = "" $clientId = "" $authUrl = "https://login.microsoftonline.com/$tenantId/oauth2/v2.0/token" $smtpServer = "" $smtpPort = $departmentsFilePath = "C:\psscr\Departments.txt" # Authenticate with Microsoft Graph $token = Get-GraphToken -tenantId $tenantId -clientId $clientId -clientSecret $clientSecret -authUrl $authUrl # Ensure that the token was successfully obtained if (-not $token) { Write-Error "Failed to obtain Microsoft Graph token. Exiting script." exit } $headers = @{ Authorization = "Bearer $token" } # Set cut-off dates $cutOffDate10Days = (Get-Date).AddDays(-10) $cutOffDate15Days = (Get-Date).AddDays(-15) # Check departments $departments = Get-Content -Path $departmentsFilePath # Initialize CSV report $currentDateTime = (Get-Date).ToString("dd-MM-yyyy_HH-mm") $csvFilePath = "C:\psscr\DailyUserLoginReport_$currentDateTime.csv" $htmlReportPath = "C:\psscr\DailyUserLoginReport_$currentDateTime.html" $csvData = @() # Process each department foreach ($dept in $departments) { $users = Get-ADUser -Filter { Department -eq $dept } -Properties LastLogonTimestamp, Manager, Enabled, UserPrincipalName, DisplayName foreach ($user in $users) { if (-not $user.Enabled) { continue } # Get the most recent LastLogon from AD $lastLogon = Get-LastLogon -userName $user.SamAccountName $lastLogonString = if ($lastLogon) { $lastLogon.ToString("yyyy-MM-dd HH:mm:ss") } else { "Never" } # Get the user's Azure AD ID $userResponse = Invoke-RestMethod -Uri "https://graph.microsoft.com/v1.0/users?$filter=userPrincipalName eq '$($user.UserPrincipalName)'" -Headers $headers # Find the user with the exact UserPrincipalName match $userId = $null foreach ($responseUser in $userResponse.value) { if ($responseUser.userPrincipalName -eq $user.UserPrincipalName) { $userId = $responseUser.id break } } #$userId = $userResponse.value[$user.UserPrincipalName].id # Ensure that a valid userId was retrieved if ($null -eq $userId) { Write-Warning "Could not retrieve userId for $($user.UserPrincipalName). Skipping..." continue } # Get the most recent last sign-in date from Azure AD using ID $lastSignInDate = Get-UserLastSignIn -userId $userId -headers $headers $lastSignInDateString = if ($lastSignInDate) { $lastSignInDate.ToString("yyyy-MM-dd HH:mm:ss") } else { "Never" } $action = "" $mailSent = $false $sessionRevoked = $false if ($lastLogon -lt $cutOffDate10Days -and $lastSignInDate -lt $cutOffDate10Days) { # Send notification to the user and manager $manager = Get-ADUser -Identity $user.Manager -Properties EmailAddress Send-Notification -userEmail $user.EmailAddress -managerEmail $manager.EmailAddress $mailSent = $true } if ($lastLogon -lt $cutOffDate15Days -and $lastSignInDate -lt $cutOffDate15Days) { # Revoke Azure AD sessions and disable the on-premises AD account # Uncomment the below line to revoke Azure AD sessions # Invoke-RestMethod -Method Post -Uri "https://graph.microsoft.com/v1.0/users/$userId/revokeSignInSessions" -Headers $headers #Disable-ADAccount -Identity $user.SamAccountName $action = "Account Disabled" $sessionRevoked = $true } $csvData += [pscustomobject]@{ samAccountName = $user.SamAccountName DisplayName = $user.DisplayName MailSentToManager = $mailSent LastLogonOnPrem = $lastLogonString LastLogonAzureAD = $lastSignInDateString SessionRevoked = $sessionRevoked Action = $action } } } # Export to CSV $csvData | Export-Csv -Path $csvFilePath -NoTypeInformation # Create and send the HTML report Create-And-Send-HTMLReport -csvData $csvData -htmlReportPath $htmlReportPath # Send the daily report to IT Send-DailyReport -reportPath $htmlReportPath Any help is appreciated why this error occurs is known to us that it is not found will this need changes in script or something else. The permissions given to Azure app is correct as is does not show permission error when running the script.Solved458Views0likes6CommentsAzure reports for Bitlocker
Hello, I have a PowerShell script for Active Directory that tells me the last time a machine was logged into and more importantly, whether it has BitLocker enabled on it. I pipe it out to an .csv file that I can easily filter to find the machines we need to check. As we're working on transitioning the BitLocker function into Intune/Azure, I'm having problems finding a way to run a similar script on Azure AD. So far, my searches have netted zero which is strange to me as I normally find scripts I can alter pretty easily. Anybody have any experience with this one?Solved352Views0likes2Comments