# Filename: run_sonar_scan.ps1 # # Description: # This script automates the SonarQube analysis for a .NET project. # It performs three main steps: # 1. Begins the SonarScanner analysis. # 2. Builds the project (which allows the scanner to analyze the code). # 3. Ends the analysis and pushes the results to the SonarQube server. # # Pre-requisites: # - .NET SDK must be installed. # - dotnet-sonarscanner tool must be installed globally. # - The 'SONAR_TOKEN' environment variable must be set with your SonarQube token. # # Usage: # 1. Open PowerShell. # 2. Navigate to the root directory of your project. # 3. Run the script: .\run_sonar_scan.ps1 # # --- Configuration --- $projectKey = "pms-dotnetcore" $sonarHost = "https://sonar.marcoaiot.com" # --- Script Body --- try { # Check if the required environment variable is set if ([string]::IsNullOrEmpty($env:SONAR_TOKEN)) { throw "ERROR: The SONAR_TOKEN environment variable is not set. Please set it and restart your terminal." } Write-Host "--- [Step 1/3] Starting SonarScanner analysis... ---" -ForegroundColor Green dotnet sonarscanner begin /k:"$projectKey" /d:sonar.host.url="$sonarHost" /d:sonar.token="$($env:SONAR_TOKEN)" # Check the exit code of the last command. A non-zero code indicates an error. if ($LASTEXITCODE -ne 0) { throw "SonarScanner 'begin' command failed with exit code $LASTEXITCODE." } Write-Host "`n--- [Step 2/3] Building the project... ---" -ForegroundColor Green dotnet build if ($LASTEXITCODE -ne 0) { throw "Dotnet 'build' command failed with exit code $LASTEXITCODE." } Write-Host "`n--- [Step 3/3] Ending SonarScanner analysis and uploading results... ---" -ForegroundColor Green dotnet sonarscanner end /d:sonar.token="$($env:SONAR_TOKEN)" if ($LASTEXITCODE -ne 0) { throw "SonarScanner 'end' command failed with exit code $LASTEXITCODE." } Write-Host "`n--- SonarQube analysis completed successfully! ---" -ForegroundColor Green } catch { # This block runs if any of the 'throw' commands are triggered Write-Host "`n$_" -ForegroundColor Red Write-Host "Script aborted due to an error." -ForegroundColor Red # Exit with a non-zero status code to indicate failure, which is important for CI/CD pipelines exit 1 }