Debug-SharePointReport.ps1

<#
.SYNOPSIS
    Run script for AsBuiltReport.Microsoft.SharePoint.

.DESCRIPTION
    On the FIRST run, this script connects Microsoft Graph and PnP.PowerShell
    BEFORE starting the report, so the sign-in browser window is visible.
    After the first run, sessions are cached and the report runs silently.

.NOTES
    Edit the CONFIG section below before running.
#>


#--------------------------------------------------------------------
# CONFIG -- edit these
#--------------------------------------------------------------------
$TenantDomain  = 'contoso.onmicrosoft.com'
$AdminUPN      = 'admin@contoso.onmicrosoft.com'
$OutputFolder  = 'C:\Reports'
$ModuleFolder  = $PSScriptRoot
#--------------------------------------------------------------------

$TenantPrefix   = ($TenantDomain -split '\.')[0]
$TenantAdminUrl = "https://${TenantPrefix}-admin.sharepoint.com"

Write-Host "=== AsBuiltReport.Microsoft.SharePoint ===" -ForegroundColor Cyan
Write-Host " Tenant : $TenantDomain"
Write-Host ""

# Import module
Import-Module (Join-Path $ModuleFolder 'AsBuiltReport.Microsoft.SharePoint.psd1') -Force -Global -ErrorAction Stop

# --- Pre-connect if not already connected ---
# This ensures the browser sign-in window is visible to the user.
# After the first successful sign-in, the token is cached and
# future runs will connect silently without any browser popup.

$GraphCtx = $null
try { $GraphCtx = Get-MgContext -ErrorAction SilentlyContinue } catch {}

if (-not ($GraphCtx -and $GraphCtx.TenantId)) {
    $GraphScopes = @('Organization.Read.All')
    Write-Host "Connecting to Microsoft Graph..." -ForegroundColor Cyan
    try {
        Connect-MgGraph -Scopes $GraphScopes -ErrorAction Stop
        Write-Host "Graph connected." -ForegroundColor Green
    } catch {
        if ($_.Exception.Message -like '*InteractiveBrowserCredential*' -or $_.Exception.Message -like '*authentication failed*') {
            Write-Host ""
            Write-Host "Interactive browser auth failed (WAM issue on this machine)." -ForegroundColor Yellow
            Write-Host "Using device code instead -- open https://microsoft.com/devicelogin and enter the code below:" -ForegroundColor Yellow
            Write-Host ""
            Connect-MgGraph -Scopes $GraphScopes -UseDeviceCode -ErrorAction Stop
            Write-Host "Graph connected." -ForegroundColor Green
        } else {
            throw
        }
    }
} else {
    Write-Host "Graph: reusing existing session ($($GraphCtx.TenantId))" -ForegroundColor DarkGray
}

$PnPConn = $null
try { $PnPConn = Get-PnPConnection -ErrorAction SilentlyContinue } catch {}

if (-not $PnPConn) {
    $ClientId = $null
    try {
        $Config = Get-Content (Join-Path $ModuleFolder 'AsBuiltReport.Microsoft.SharePoint.json') | ConvertFrom-Json
        $ClientId = $Config.Options.PnP.ClientId
    } catch {}

    if ($ClientId -and $ClientId -ne '') {
        Write-Host "Connecting PnP.PowerShell (browser window will open)..." -ForegroundColor Cyan
        Connect-PnPOnline -Url $TenantAdminUrl -ClientId $ClientId -Interactive -ErrorAction Stop
        Write-Host "PnP connected." -ForegroundColor Green
    } else {
        Write-Host "PnP: no ClientId configured -- SharePoint sections will be skipped." -ForegroundColor Yellow
    }
} else {
    Write-Host "PnP: reusing existing session" -ForegroundColor DarkGray
}

Write-Host ""
Write-Host "Running report..." -ForegroundColor Cyan
Write-Host ""

# Run the report -- sessions are already established above
$ReportConfigPath = Join-Path $ModuleFolder 'AsBuiltReport.Microsoft.SharePoint.json'
$BaseConfigPath   = Join-Path $ModuleFolder 'AsBuiltReport.json'

$ReportParams = @{
    Report            = 'Microsoft.SharePoint'
    Target            = $TenantDomain
    Username          = $AdminUPN
    OutputFolderPath  = $OutputFolder
    Format            = 'Word'
    EnableHealthCheck = $true
    ErrorAction       = 'Stop'
}
if (Test-Path $ReportConfigPath) { $ReportParams['ReportConfigFilePath'] = $ReportConfigPath }
if (Test-Path $BaseConfigPath)   { $ReportParams['AsBuiltConfigFilePath'] = $BaseConfigPath }

try {
    New-AsBuiltReport @ReportParams
    Write-Host ""
    Write-Host "Report completed successfully." -ForegroundColor Green
} catch {
    Write-Host "FAILED: $($_.Exception.Message)" -ForegroundColor Red
    $_.ScriptStackTrace -split "`n" | ForEach-Object { Write-Host " $_" -ForegroundColor DarkRed }
}