PowerCds.psm1


# Discover and load function scripts
$scriptFiles = @(Get-ChildItem -Path "$PSScriptRoot\Functions" -Include "*.ps1" -Recurse);
foreach ($scriptFile in $scriptFiles) {
    $scriptPath = $scriptFile.FullName;
    Write-Verbose " > Loading function file '$scriptPath'";
    try {
        . $scriptPath;
        Write-Verbose " > Loading function file '$scriptPath' => OK !";
    }
    catch {
        $errorMessage = $_.Exception.Message;
        Write-Verbose " > Loading function file '$scriptPath' => KO ! Reason = '$errorMessage'";
    }
}

# Install and Import required modules
$requiredModules = @("Microsoft.Xrm.Tooling.CrmConnector.PowerShell", "Microsoft.Xrm.OnlineManagementAPI")
foreach ($module in $requiredModules) {
    if (-not(Get-Module -ListAvailable -Name $module)) {
        Write-Verbose "$module does not exist";
        Install-Module -Name $module -Scope CurrentUser -SkipPublisherCheck -Force -Confirm:$false
    }
    Import-Module -Name $module;
}

# Initialize proxy cache for better performances
$Global:ConnectorsCache = @{ };

# Provision dedicate appdata folder
$Global:PowerCdsModuleFolderPath = [System.IO.Path]::Combine($env:APPDATA, "PowerCds");
New-Item -ItemType Directory -Path $Global:PowerCdsModuleFolderPath -Force | Out-Null;

Write-Verbose "Module folder initialized : $($Global:PowerCdsModuleFolderPath)";

# Initialize tracing file
$timestamp = Get-date -format "yyyy-MM-dd -- HH-mm-ss";
New-Item -ItemType Directory -Path $Global:PowerCdsModuleFolderPath -Name "Logs" -Force | Out-Null;
$Global:LogFolderPath = [System.IO.Path]::Combine($Global:PowerCdsModuleFolderPath, "Logs");
$Global:LogFilePath = [System.IO.Path]::Combine($Global:LogFolderPath, "$timestamp.log");