Unattended Scripts to connect

Anonymous
2023-03-30T05:26:56.15+00:00

For the MFA enabled account I need to run the PowerShell scripts without any user intersection for the below connections

1.Connect-MsolService

2.Connect-SPOService

3.Connect-MicrosoftTeams

Please help to get the steps to connect.

Windows Server PowerShell
Windows Server PowerShell
Windows Server: A family of Microsoft server operating systems that support enterprise-level management, data storage, applications, and communications.PowerShell: A family of Microsoft task automation and configuration management frameworks consisting of a command-line shell and associated scripting language.
5,362 questions
PowerShell
PowerShell
A family of Microsoft task automation and configuration management frameworks consisting of a command-line shell and associated scripting language.
2,050 questions
0 comments No comments
{count} votes

2 answers

Sort by: Most helpful
  1. Sedat SALMAN 13,160 Reputation points
    2023-03-30T06:50:03.1466667+00:00

    hope this works for you

    To connect to these services with an MFA-enabled account without user interaction, you can use the Connect-ExchangeOnline cmdlet with the -AppId and -CertificateThumbprint parameters. You'll need to create an Azure AD app registration, generate a self-signed certificate, and grant the required permissions.

    Create an Azure AD app registration

    • Go to "Azure Active Directory" > "App registrations" > "New registration"
    • Note down the "Application (client) ID" for later use

    Generate a self-signed certificate

    New-SelfSignedCertificate -CertStoreLocation Cert:\CurrentUser\My -Subject "CN=YourAppRegistrationName" -KeySpec KeyExchange -NotAfter (Get-Date).AddYears(1)
    
    

    Note down the certificate thumbprint

    Export the certificate public key

    open certlm.msc > Navigate to "Personal" > "Certificates" > export the certificate as a .cer file

    Upload the certificate to the Azure AD app registration: a. Go back to the Azure portal and navigate to the app registration you created b. Go to "Certificates & secrets" > "Certificates" > "Upload certificate" c. Upload the exported .cer file

    Grant the required permissions for the services: a. Go to "API permissions" > "Add a permission" b. Add the required permissions for each service:

    1. For Connect-MsolService, add "Azure Active Directory Graph" > "Application permissions" > "Directory.Read.All"
      1. For Connect-SPOService, add "Office 365 SharePoint Online" > "Application permissions" > "Sites.FullControl.All"
      2. For Connect-MicrosoftTeams, add "Microsoft Graph" > "Application permissions" > "Group.ReadWrite.All"
      c. Click "Add permissions" and then "Grant admin consent" to grant the permissions

    Connect to the services using the Connect-ExchangeOnline cmdlet

    $AppId = "<Your-App-Client-ID>"
    $TenantId = "<Your-Tenant-ID>"
    $CertificateThumbprint = "<Your-Certificate-Thumbprint>"
    $Credential = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $AppId, (Get-ChildItem -Path Cert:\CurrentUser\My\$CertificateThumbprint)
    Connect-MsolService -Credential $Credential -TenantId $TenantId
    Connect-SPOService -Url "https://yourtenantname-admin.sharepoint.com" -Credential $Credential
    Connect-MicrosoftTeams -TenantId $TenantId -ApplicationId $AppId -CertificateThumbprint $CertificateThumbprint
    
    

    Replace <Your-App-Client-ID>, <Your-Tenant-ID>, and <Your-Certificate-Thumbprint> with your specific values. After executing these commands, you will be connected to the specified services without user interaction.


  2. MÜLLER Markus 0 Reputation points
    2024-01-16T10:42:05.3366667+00:00

    We have also the Problem with an Connect-MSOL if we use this How To. But we use now the Connect-MGGraph and it works. We have realized a script for Password expire as example:

    # Connect to Microsoft Graph With ClientID = App Id registered in Azure 
    # Certificate in user Cert on Server
    Connect-MgGraph -ClientID YourAppID -CertificateThumbprint YourThumbprint -TenantID YourTenantID
    # Set the notification threshold - days before password expires
    $NotificationThreshold = 21
    $PasswordExpiryThreshold = 90 #By default 90 days Password expiry
    #Path for Log File
    $LogFilePath = "C:\yourPath.Log"
    #Function to Add Content to a Log File
    Function Write-Log {
      [CmdletBinding()]
      Param ([Parameter(Mandatory=$true)][string]$Message) 
      Process{
            #Add Message to Log File with timestamp
            "$([datetime]::Now) : $Message" | Out-File -FilePath $LogFilePath -append;
            #Write the log message to the screen
            Write-host $([datetime]::Now) $Message
        }
    }
     
     
    # Get all users for Germany without exclude params
    $users =  Get-MgUser -All -Filter "(country eq 'Germany') or (country eq 'Deutschland') and accountEnabled eq true" -Property Id, DisplayName, UserPrincipalName,Mail,UserType, AccountEnabled,PasswordPolicies,lastPasswordChangeDateTime,JobTitle
    $AllUsers = $users | Where-Object { ($_.DisplayName -notlike "DE_*") -and ($_.DisplayName -notlike "*EXTERN*") -and ($_.DisplayName -notlike "*STANDARD*") }
    # Iterate through each user
    ForEach ($User in $AllUsers)
    {
        # Skip disabled accounts and users with Password never Expire flag
        If (!$User.AccountEnabled -or $User.PasswordPolicies -contains "xDisablePasswordExpiration" -or $User.userType -eq "Guest") {
            continue
        }
        # Get user's password Expiry Date
    
        $PasswordExpiryDate = $User.lastPasswordChangeDateTime.AddDays($PasswordExpiryThreshold)
        # Calculate the remaining days
        $RemainingDays = ($PasswordExpiryDate - (Get-Date)).Days
        # Check if the remaining days are within the notification threshold
        If ($RemainingDays -le $NotificationThreshold) {
            # Check job title for 'Test'
            if ($User.JobTitle -eq 'Test') {
                # Send an email notification specific to 'Test'
                $EmailBody = "
                   Hallo $($User.DisplayName),
    <br/><br/>
                Please change Password
    <br/><br/>
                Follow this Steps<br/>
    <ol>
    <li>Sign on Office.com (https://www.office.com)</li>
    <li>xxxxxxxTextxxxxxxxxxxxx</li>
    <li>xxxxxxxTextxxxxxxxxxxxx</li>
    <li>xxxxxxxTextxxxxxxxxxxxx</li>
    <li>xxxxxxxTextxxxxxxxxxxxx</li>
    <br/><br/>
    </ol>
    <br/>
    <br/>
    <strong>xxxxxxxTextxxxxxxxxxxxx:</strong>
    <ol>
    <li>xxxxxxxTextxxxxxxxxxxxx</li>
    <li>xxxxxxxTextxxxxxxxxxxxx</li>
    <li><strong>xxxxxxxTextxxxxxxxxxxxx</strong>: xxxxxxxTextxxxxxxxxxxxx</li>   
    <li><strong>xxxxxxxTextxxxxxxxxxxxx</strong>: xxxxxxxTextxxxxxxxxxxxx</li>
    </ol>
                vielen Dank,<br/>
                TxxxxxxxTextxxxxxxxxxxxx
            "
            }
            else {
                # Send a generic email notification for other job titles
                $EmailBody = "
                     Hallo $($User.DisplayName),
    <br/><br/>
                Please change Password.
    <br/><br/>
                Please change Password<br/>
                xxxxxxxTextxxxxxxxxxxxx<br/>
    
    <br/>
    <strong>xxxxxxxTextxxxxxxxxxxxx:</strong>
    <ol>
    <li>xxxxxxxTextxxxxxxxxxxxx</li>
    <li>xxxxxxxTextxxxxxxxxxxxx</li>
    <li><strong>xxxxxxxTextxxxxxxxxxxxx</strong>:xxxxxxxTextxxxxxxxxxxxx</li>   
    <li><strong>xxxxxxxTextxxxxxxxxxxxxt</strong>: xxxxxxxTextxxxxxxxxxxxx</li>
    </ol>
                xxxxxxxTextxxxxxxxxxxxx,<br/>
                xxxxxxxTextxxxxxxxxxxxx
            "
            }
            $MailParams = @{
                Message = @{
                    Subject = "Your Password expires"
                    Importance = "High"
                    Body = @{
                        ContentType = "html"
                        Content = $EmailBody
                    }
                    ToRecipients = @(
                        @{
                            EmailAddress = @{
                                Address = $User.Mail
                            }
                        }
                    )
                }
            }
            # Send the email using Microsoft Graph
            Send-MgUserMail -UserId $User.Mail -BodyParameter $MailParams
            #Write to Log File
            Write-Log "Password Expiration Notification sent to user $($User.Mail) - Password Expires on $PasswordExpiryDate"
        }
    }
    
    0 comments No comments