MyPSFunctions.Cyber.ps1

<#
    ===========================================================================
     Created with: SAPIEN Technologies, Inc., PowerShell Studio
     Created on: 10/26/2023 7:04 PM
     Created by: John@MyPSFunctions.com
     Organization: MyPSFunctions
     Filename: MyPSFunctions.Cyber.ps1
    -------------------------------------------------------------------------
     Module Name: MyPSFunctions.Cyber
    ===========================================================================
#>

#region Modules
Function Install-MyPSFunctionsModules
{
    [CmdletBinding()]
    param
    (
        [Parameter(Position = 1)]
        [switch]$EXO,
        [Parameter(Position = 2)]
        [switch]$MSOnline,
        [Parameter(Position = 3)]
        [Switch]$AAD,
        [Parameter(Position = 4)]
        [switch]$Teams,
        [Parameter(Position = 5)]
        [Switch]$SPO,
        [Parameter(Position = 7)]
        [switch]$All
    )
    
    Try
    {
        Read-Host "Did you open powershell with admin rights - Press Enter to Continue or CTRL + C to Cancel"
        # Install MSOnline Module (Force & Update & Remove old version)
        If ($EXO)
        {
            Install-Module -Name PowerShellGet -SkipPublisherCheck -Scope CurrentUser -Force -AllowClobber -Confirm:$False; Write-Host "Successfully install PowershellGet Module"
            Install-Module -Name ExchangeOnlineManagement -SkipPublisherCheck -Scope CurrentUser -Force -AllowClobber -Confirm:$False; Write-Host "Successfully install (New) Exchange Online Module"
        }
        # Install MSOnline Module (Force & Update & Remove old version)
        If ($MSOnline) { Install-Module -Name MSOnline -SkipPublisherCheck -Scope CurrentUser -Force -AllowClobber -Confirm:$False; Write-Host "Successfully install MSOnline Module" }
        # Install Azure AD module (Force & Update & Remove old version)
        If ($AAD)
        {
            Install-Module -Name AzureADPreview -SkipPublisherCheck -Scope CurrentUser -Force -AllowClobber -Confirm:$False; Write-Host "Successfully install AzureAD Preview Module"
            Install-Module -Name Microsoft.Graph -SkipPublisherCheck -Scope CurrentUser -Force -AllowClobber -Confirm:$False; Write-Host "Successfully install Microsoft Graph Module"
            Install-Module -Name Microsoft.Graph.beta -SkipPublisherCheck -Scope CurrentUser -Force -AllowClobber -Confirm:$False; Write-Host "Successfully install Microsoft Graph Beta Module"
            
        }
        # Install Microsoft Teams Module (Force & Update & Remove old version)
        If ($Teams) { Install-Module -Name MicrosoftTeams -SkipPublisherCheck -Scope CurrentUser -Force -AllowClobber -Confirm:$False; Write-Host "Successfully install Teams Module" }
        # Install Sharepoint Module (Force & Update & Remove old version)
        if ($SPO)
        {
            Install-Module -Name Microsoft.Online.SharePoint.PowerShell -SkipPublisherCheck -Scope CurrentUser -Force -AllowClobber -Confirm:$False; Write-Host "Successfully install Sharepoint Module"
            Install-Module -Name SharePointPnPPowerShellOnline -SkipPublisherCheck -Scope CurrentUser -Force -AllowClobber -Confirm:$False; Write-Host "Successfully install SharePoint PnP PowerShell Online"
            Install-Module -Name PnP.PowerShell -SkipPublisherCheck -Scope CurrentUser -Force -AllowClobber -Confirm:$False; Write-Host "Successfully install PnP.PowerShellModule"
        }
        # install all the Modules
        if ($All)
        {
            # Install EXO Module (Force & Update & Remove old version)
            Install-Module -Name PowerShellGet -SkipPublisherCheck -Scope CurrentUser -Force -AllowClobber -Confirm:$False; Write-Host "Successfully install PowershellGet Module"
            Install-Module -Name ExchangeOnlineManagement -SkipPublisherCheck -Scope CurrentUser -Force -AllowClobber -Confirm:$False; Write-Host "Successfully install (New) Exchange Online Module"
            # Install MSOnline Module (Force & Update & Remove old version)
            Install-Module -Name MSOnline -SkipPublisherCheck -Scope CurrentUser -Force -AllowClobber -Confirm:$False; Write-Host "Successfully install MSOnline Module"
            # Install Azure AD module (Force & Update & Remove old version)
            Install-Module -Name AzureADPreview -SkipPublisherCheck -Scope CurrentUser -Force -AllowClobber -Confirm:$False; Write-Host "Successfully install AzureAD Preview Module"
            Install-Module -Name Microsoft.Graph -SkipPublisherCheck -Scope CurrentUser -Force -AllowClobber -Confirm:$False; Write-Host "Successfully install Microsoft Graph Module"
            Install-Module -Name Microsoft.Graph.beta -SkipPublisherCheck -Scope CurrentUser -Force -AllowClobber -Confirm:$False; Write-Host "Successfully install Microsoft Graph Beta Module"
            # Install Microsoft Teams Module (Force & Update & Remove old version)
            Install-Module -Name MicrosoftTeams -SkipPublisherCheck -Scope CurrentUser -Force -AllowClobber -Confirm:$False; Write-Host "Successfully install Teams Module"
            # Install Sharepoint Module (Force & Update & Remove old version)
            Install-Module -Name Microsoft.Online.SharePoint.PowerShell -SkipPublisherCheck -Scope CurrentUser -Force -AllowClobber -Confirm:$False; Write-Host "Successfully install Sharepoint Module"
            Install-Module -Name SharePointPnPPowerShellOnline -SkipPublisherCheck -Scope CurrentUser -Force -AllowClobber -Confirm:$False; Write-Host "Successfully install SharePoint PnP PowerShell Online"
            Install-Module -Name PnP.PowerShell -SkipPublisherCheck -Scope CurrentUser -Force -AllowClobber -Confirm:$False; Write-Host "Successfully install PnP.PowerShellModule"
            # Install Other Module
            Install-Module -Name AIPService -SkipPublisherCheck -Scope CurrentUser -Force -AllowClobber -Confirm:$False; Write-Host "Successfully install AIPService Module"
            Install-Module -Name Mailozaurr -SkipPublisherCheck -Scope CurrentUser -Force -AllowClobber -Confirm:$False; Write-Host "Successfully install Mailozaurr Module"
            Install-Module -Name Posh-SSH -SkipPublisherCheck -Force -AllowClobber -Confirm:$False; Write-Host "Successfully install Posh-SSH Module"
            Install-Module -Name ORCA -SkipPublisherCheck -Scope CurrentUser -Force -AllowClobber -Confirm:$False; Write-Host "Successfully install ORCA Module"
            Install-Module -Name AzureRM -SkipPublisherCheck -Scope CurrentUser -Force -AllowClobber -Confirm:$False; Write-Host "Successfully install AzureRM Module"
            Install-Module -Name Az -SkipPublisherCheck -Scope CurrentUser -Force -AllowClobber -Confirm:$False; Write-Host "Successfully install Az Modules"
            Install-Module -Name Microsoft.PowerApps.Administration.PowerShell -SkipPublisherCheck -Scope CurrentUser -Force -AllowClobber -Confirm:$False; Write-Host "Successfully install Microsoft.PowerApps.Administration.PowerShell Module"
            Install-Module -Name Microsoft.PowerApps.PowerShell -SkipPublisherCheck -Scope CurrentUser -Force -AllowClobber -Confirm:$False; Write-Host "Successfully install Microsoft.PowerApps.PowerShell Module"
            Install-Module -Name PSTeams -SkipPublisherCheck -Scope CurrentUser -Force -AllowClobber -Confirm:$False; Write-Host "Successfully install PSTeams Module"
            Install-Module -Name PSBlackListChecker -SkipPublisherCheck -Scope CurrentUser -Force -AllowClobber -Confirm:$False; Write-Host "Successfully install PSBlackListChecker Module"
            Install-Module -Name PowerShellAI -SkipPublisherCheck -Scope CurrentUser -Force -AllowClobber -Confirm:$False; Write-Host "Successfully install PowerShellAI Module"
            Install-Module -Name MSIdentityTools -SkipPublisherCheck -Scope CurrentUser -Force -AllowClobber -Confirm:$False; Write-Host "Successfully install MS Identity Tools Module"
            Install-Module -Name ImportExcel -SkipPublisherCheck -Scope CurrentUser -Force -AllowClobber -Confirm:$False; Write-Host "Successfully install ImportExcel Module"
        }
    }
    Catch
    {
        $ErrorMessage = $Error[0].Exception.Message
        $CMDLet = $Error[0].InvocationInfo.Line
        Write-Host "Failed to run the following CMDLet: $CMDLet"
        Write-host "Failed with Error:$ErrorMessage"
    }
}

Function Update-MyPSFunctionsModules
{
    [CmdletBinding()]
    param ()
    Read-Host "Did you open powershell with admin rights - Press Enter to Continue or CTRL + C to Cancel"
    Try
    {
        # Install EXO Module (Force & Update & Remove old version)
        Update-Module -Name PowerShellGet -Force -confirm:$False
        Update-Module -Name ExchangeOnlineManagement -Force -confirm:$False; Write-Host "Successfully Update (New) Exchange Online Module"
        # Install MSOnline Module (Force & Update & Remove old version)
        Update-Module -Name MSOnline -Force -confirm:$False; Write-Host "Successfully Update MSOnline Module"
        # Install Azure AD module (Force & Update & Remove old version)
        Update-Module -Name AzureADPreview -Force -confirm:$False; Write-Host "Successfully Update AzureAD Preview Module"
        Update-Module -Name Microsoft.Graph -Force -confirm:$False; Write-Host "Successfully Update Microsoft Graph Module"
        Update-Module -Name Microsoft.Graph.beta -Force -confirm:$False; Write-Host "Successfully Update Microsoft Graph Beta Module"
        # Install Microsoft Teams Module (Force & Update & Remove old version)
        Update-Module -Name MicrosoftTeams -Force -confirm:$False; Write-Host "Successfully Update Teams Module"
        # Install Sharepoint Module (Force & Update & Remove old version)
        Update-Module -Name Microsoft.Online.SharePoint.PowerShell -Force -confirm:$False; Write-Host "Successfully Update Sharepoint Module"
        Update-Module -Name SharePointPnPPowerShellOnline -Force -confirm:$False; Write-Host "Successfully Update Sharepoint Module"
        Update-Module -Name PnP.PowerShell -Force -confirm:$False; Write-Host "Successfully Update PnP Module"
        # Install Other Module
        Update-Module -Name AIPService -Force -confirm:$False; Write-Host "Successfully Update AIPService Module"
        Update-Module -Name Mailozaurr -Force -confirm:$False; Write-Host "Successfully Update Mailozaurr Module"
        Update-Module -Name Posh-SSH -Force -confirm:$False; Write-Host "Successfully Update Posh-SSH Module"
        Update-Module -Name ORCA -Force -confirm:$False; Write-Host "Successfully Update ORCA Module"
        Update-Module -Name AzureRM -Force -confirm:$False; Write-Host "Successfully Update AzureRM Module"
        Update-Module -Name Az -Force -confirm:$False; Write-Host "Successfully Update Az Modules"
        Update-Module -Name PSBlackListChecker -Force -confirm:$False; Write-Host "Successfully Update PSBlackListChecker Module"
        Update-Module -Name PowerShellAI -Force -confirm:$False; Write-Host "Successfully Update PowerShellAI Module"
        Update-Module -Name MSIdentityTools -Force -confirm:$False; Write-Host "Successfully Update MS Identity Tools Module"
        Update-Module -Name ImportExcel -Force -confirm:$False; Write-Host "Successfully Update ImportExcel Module"
        
        
    }
    Catch
    {
        $ErrorMessage = $Error[0].Exception.Message
        $CMDLet = $Error[0].InvocationInfo.Line
        Write-Host "Failed to run the following CMDLet: $CMDLet"
        Write-host "Failed with Error:$ErrorMessage"
    }
}

#endregion


#region Office365

Function Recon-MyUserName
{
    [CmdletBinding()]
    param
    (
        [Parameter(Mandatory = $true,
                   Position = 1)]
        [String]$UserName
    )
    
    $UserNameURL = "https://login.microsoftonline.com/getuserrealm.srf?login=" + $UserName + "&xml=1"
    $Data = Start-Process $UserNameURL
    Write-Log warning -Message "Please check your default browser a new Tab has been opened for User Information (Valid office 365 login, domain configuration (federated or managed, "
    $Domain = $UserName.Substring($UserName.LastIndexOf("@") + 1)
    
    $TenantIDURL = "https://login.microsoftonline.com/" + $Domain + "/.well-known/openid-configuration"
    Start-Process $TenantIDURL
    Write-Log warning -Message "Please check your default browser a new Tab has been opened for Tenant information for OAuth connection"
}
#endregion

#region MgGraph
Function Connect-MyMgGraphUsingToken
{
    [CmdletBinding()]
    param
    (
        [Parameter(Mandatory = $true,
                   Position = 1)]
        [String]$Token
    )
    
    Connect-MgGraph -AccessToken ($Token | ConvertTo-SecureString -AsPlainText -Force)
    $MgContext = Get-MgContext
    $TenantId = $MgContext.TenantId
    $Scopes = $MgContext.Scopes
    $AuthType = $MgContext.AuthType
    $TokenCredentialType = $MgContext.TokenCredentialType
    $Account = $MgContext.Account
    Write-Log Info -Message "The Account: $Account"
    Write-Log Info -Message "The TenantID: $TenantId"
    Write-Log Info -Message "Authentication Type: $AuthType - TokenCredentialType: $TokenCredentialType "
    Write-Log Info -Message "The Scope is:"
    $Scopes
}

Function Enumarate-MyMgUsersOnPremVsCloudOnly
{
    [CmdletBinding()]
    param ()
    
    $OnPremiseMgUsers = Get-MgUser -All | ?{ $_.OnPremisesSecurityIdentifier -ne $null }
    $SelectedOnPremiseMgUsers = $OnPremiseMgUsers | select AccountEnabled, DisplayName, JobTitle, Mail, OtherMails, UserPrincipalName, Manager, OnPremisesImmutableId, OnPremisesLastSyncDateTime, OnPremisesSyncEnabled, OnPremisesUserPrincipalName
    $CloudOnlyMgUsers = Get-MgUser -All | ?{ $_.OnPremisesSecurityIdentifier -eq $null }
    $SelectedCloudOnlyMgUsers = $CloudOnlyMgUsers | select AccountEnabled, DisplayName, JobTitle, Mail, OtherMails, UserPrincipalName, Manager, OnPremisesImmutableId, OnPremisesLastSyncDateTime, OnPremisesSyncEnabled, OnPremisesUserPrincipalName
    $DateFull = Get-Date -Format "ddMMyyyy_HH-mm-ss"
    $ExcelFileName = ".\Report_MgUsers_" + $DateFull + ".xlsx"
    $SelectedOnPremiseMgUsers | Export-Excel -Path $ExcelFileName -WorksheetName "OnPremiseUsers" -Title "OnPremise Users" -TitleBold -TableName "OnPremiseUsers" -TableStyle Medium9
    $SelectedCloudOnlyMgUsers | Export-Excel -Path $ExcelFileName -WorksheetName "CloudOnlyUsers" -Title "Cloud-Only Users" -TitleBold -TableName "CloudOnlyUsers" -TableStyle Medium9 -Append
}


Function Enumerate-MyMgOwnedAccountsByUser
{
    [CmdletBinding()]
    param
    (
        [Parameter(Mandatory = $true,
                   Position = 1)]
        [String]$UserID
    )
    
    $MgUserOwnedObjects = Get-MgUserOwnedObject -UserId $UserID

    #Initiate the Hash Table
    [Int]$i = 1
    $Table = $Null
    $Table = @()
    $Count = ($MgUserOwnedObjects | Measure).count
    
    ForEach ($MgUserOwnedObject in $MgUserOwnedObjects)
    {
        $Type = $Null
        $Type = $MgUserOwnedObject.additionalProperties.'@odata.type'
        $appId = $Null
        $appId = $MgUserOwnedObject.additionalProperties.appId
        $createdDateTime = $Null
        $createdDateTime  = $MgUserOwnedObject.additionalProperties.createdDateTime
        $displayName = $Null
        $displayName = $MgUserOwnedObject.additionalProperties.displayName
        $signInAudience = $Null
        $signInAudience = $MgUserOwnedObject.additionalProperties.signInAudience
        $verifiedPublisher = $Null
        $verifiedPublisher  = $MgUserOwnedObject.additionalProperties.verifiedPublisher
        $web = $Null
        $web = $MgUserOwnedObject.additionalProperties.web
        
        Write-log Warning -message "The script is analyzing $displayName ….. --- $i/$Count"
        
        $Table += New-object PSobject -Property ([Ordered] @{
                DisplayName                  = $displayName;
                Type        = $Type;
                AppId                  = $appId;
                CreatedDateTime = $createdDateTime;
                SignInAudience = $signInAudience;
                VerifiedPublisher = $verifiedPublisher;
                URL            = $web;
            })
        
        $i++
    }
    
    $Table | ft
}

Function Enumerate-MyMgGlobalAdmins
{

    $RoleId = (Get-MgDirectoryRole -Filter "DisplayName eq 'Global Administrator'").Id
    $MgGlobalAdmins =Get-MgDirectoryRoleMember -DirectoryRoleId $RoleId
    #Initiate the Hash Table
    [Int]$i = 1
    $Table = $Null
    $Table = @()
    $Count = ($MgGlobalAdmins | Measure).count
    
    ForEach ($MgGlobalAdmin in $MgGlobalAdmins)
    {
        $Type = $Null
        $Type = $MgGlobalAdmin.AdditionalProperties.'@odata.type'
        $displayName = $Null
        $displayName = $MgGlobalAdmin.AdditionalProperties.displayName
        $Mail  = $Null
        $Mail = $MgGlobalAdmin.AdditionalProperties.mail
        $userPrincipalName = $Null
        $userPrincipalName = $MgGlobalAdmin.AdditionalProperties.userPrincipalName
        Write-log Warning -message "The script is analyzing $displayName ….. --- $i/$Count"
        
        $Table += New-object PSobject -Property ([Ordered] @{
                displayName                  = $displayName;
                Type        = $Type;
                Mail                  = $Mail;
                userPrincipalName                      = $userPrincipalName;
            })
        
        $i++
    }
    $Table | ft
    
}

Function Enumerate-MyMgDirectoryRoleAdmins
{
    
    $MgDirectoryRoles = Get-MgDirectoryRole
    
    #Initiate the Hash Table
    [Int]$i = 1
    $Count = ($MgDirectoryRoles | Measure).count
    $DateFull = Get-Date -Format "ddMMyyyy_HH-mm-ss"
    $ExcelFile = ".\Report_DirectoryRoles_" + $DateFull + ".xlsx"
    $MgDirectoryRoles | Select id,Displayname,Description | Export-Excel -Path $ExcelFile -WorksheetName "DirectoryRoles" -Title "Directory Roles" -TitleBold -TableName "DirectoryRoles" -TableStyle Medium9

    $Table = $Null
    $Table = @()
    ForEach ($MgDirectoryRole in $MgDirectoryRoles)
    {
        $MgDirectoryRole_Id = $Null
        $MgDirectoryRole_Id = $MgDirectoryRole.Id
        $MgDirectoryRole_DisplayName = $Null
        $MgDirectoryRole_DisplayName = $MgDirectoryRole.DisplayName
        Write-log Warning -message "The script is analyzing $MgDirectoryRole_DisplayName ($MgDirectoryRole_Id) ….. --- $i/$Count"

        $MgAdmins = Get-MgDirectoryRoleMember -DirectoryRoleId $MgDirectoryRole_Id
        #Initiate the Hash Table

        $MgAdmins_Count = ($MgAdmins | Measure).count
        [Int]$ii = 1
        ForEach ($MgAdmin in $MgAdmins)
        {
            $MgAdmin_Type = $Null
            $MgAdmin_Type = $MgAdmin.AdditionalProperties.'@odata.type'
            $MgAdmin_displayName = $Null
            $MgAdmin_displayName = $MgAdmin.AdditionalProperties.displayName
            $MgAdmin_Mail = $Null
            $MgAdmin_Mail = $MgAdmin.AdditionalProperties.mail
            $MgAdmin_userPrincipalName = $Null
            $MgAdmin_userPrincipalName = $MgAdmin.AdditionalProperties.userPrincipalName
            Write-log Warning -message "The script is analyzing $MgAdmin_displayName ….. --- $i/$MgAdmins_Count"
            
            $Table += New-object PSobject -Property ([Ordered] @{
                    UisplayName          = $MgAdmin_displayName;
                    Type              = $MgAdmin_Type;
                    Mail              = $MgAdmin_Mail;
                    UserPrincipalName = $MgAdmin_userPrincipalName;
                    DirectoryRole      = $MgDirectoryRole_DisplayName;
                })
            
            $ii++
        }

            $i++
    }
    $Table | Export-Excel -Path $ExcelFile -WorksheetName "DirectoryRolesAssigned" -Title "Directory Roles Assigned" -TitleBold -TableName "DirectoryRolesAssigned" -TableStyle Medium9 -append
    Write-log Warning -message "The following report was generated: $ExcelFile"
}

#endregion

#region Azure
#endregion