functions/Invoke-RegentScheduledImports.ps1

Import-Module "$PsScriptRoot\Import-RegentSolution.ps1"
Import-Module "$PsScriptRoot\Get-Config.ps1"

Import-Module crm-datatools
function Invoke-RegentScheduledImports {
  ##############################
  #.SYNOPSIS
  # Uses a config file in the solutions repo to execute all scheduled solution imports. Intended to be run as a scheduled task
  #
  #.DESCRIPTION
  # This function reads a file called "solution-imports.json" in the solutions repo and runs Import-RegentSolution on each job. The configuration data is generated easily with Move-RegentSolution. This function is intended to run regularly as scheduled job.
  #
  #.EXAMPLE
  # To execute all scheduled jobs, just run:
  # Invoke-RegentScheduledImports
  #
  ##############################
  $ErrorActionPreference = "Stop"
  $configPath = "$(((Get-Config).RepositoryPath))\solution-imports.json"
  if (Test-Path $configPath) {
    $config = Get-Content $configPath | ConvertFrom-Json
  }
  # Frequently, there are no scheduled imports, in which case $config will be null
  if ($config) {

    # If it isn't an array already, wrap $config in an array for more uniform handling
    if (-not $config.Length) {
      $jobs = @($config)
    }
    else {
      $jobs = $config
    }
    # Now we'll iterate over all the jobs where the scheduled time is now or in the past
    $now = Get-Date
    $jobs | Where-Object {
      $_.Time -le $now.ToUniversalTime()
    }`
      | ForEach-Object {      
      try {
        $ErrorActionPreference = "Stop"
        $pw = $_.Password | ConvertTo-SecureString
        Import-RegentSolution `
          -SolutionName $_.SolutionName `
          -CrmInstance $_.CrmInstance `
          -Managed $_.Managed `
          -PublishCustomizations $_.PublishCustomizations `
          -Emails $_.Emails `
          -Credential (New-Object System.Management.Automation.PSCredential `
            -ArgumentList $_.UserName, $pw )
      }
      catch {
        $ErrorActionPreference = "SilentlyContinue"
      }
    }

    # Write out the remaining jobs back to the json file for import later
    $jobs | Where-Object {
      $_.Time -gt $now.ToUniversalTime()
    } | ConvertTo-Json > $configPath
  }
  else {
    Write-Output "No config found at $configPath"
  }
}