PSDracoon.psm1

$script:ModuleRoot = $PSScriptRoot
$script:ModuleVersion = (Import-PowerShellDataFile -Path "$($script:ModuleRoot)\PSDracoon.psd1").ModuleVersion

# Detect whether at some level dotsourcing was enforced
$script:doDotSource = Get-PSFConfigValue -FullName PSDracoon.Import.DoDotSource -Fallback $false
if ($PSDracoon_dotsourcemodule) { $script:doDotSource = $true }

<#
Note on Resolve-Path:
All paths are sent through Resolve-Path/Resolve-PSFPath in order to convert them to the correct path separator.
This allows ignoring path separators throughout the import sequence, which could otherwise cause trouble depending on OS.
Resolve-Path can only be used for paths that already exist, Resolve-PSFPath can accept that the last leaf my not exist.
This is important when testing for paths.
#>


# Detect whether at some level loading individual module files, rather than the compiled module was enforced
$importIndividualFiles = Get-PSFConfigValue -FullName PSDracoon.Import.IndividualFiles -Fallback $false
if ($PSDracoon_importIndividualFiles) { $importIndividualFiles = $true }
if (Test-Path (Resolve-PSFPath -Path "$($script:ModuleRoot)\..\.git" -SingleItem -NewChild)) { $importIndividualFiles = $true }
if ("<was compiled>" -eq '<was not compiled>') { $importIndividualFiles = $true }
    
function Import-ModuleFile
{
    <#
        .SYNOPSIS
            Loads files into the module on module import.
         
        .DESCRIPTION
            This helper function is used during module initialization.
            It should always be dotsourced itself, in order to proper function.
             
            This provides a central location to react to files being imported, if later desired
         
        .PARAMETER Path
            The path to the file to load
         
        .EXAMPLE
            PS C:\> . Import-ModuleFile -File $function.FullName
     
            Imports the file stored in $function according to import policy
    #>

    [CmdletBinding()]
    Param (
        [string]
        $Path
    )
    
    $resolvedPath = $ExecutionContext.SessionState.Path.GetResolvedPSPathFromPSPath($Path).ProviderPath
    if ($doDotSource) { . $resolvedPath }
    else { $ExecutionContext.InvokeCommand.InvokeScript($false, ([scriptblock]::Create([io.file]::ReadAllText($resolvedPath))), $null, $null) }
}

#region Load individual files
if ($importIndividualFiles)
{
    # Execute Preimport actions
    foreach ($path in (& "$ModuleRoot\internal\scripts\preimport.ps1")) {
        . Import-ModuleFile -Path $path
    }
    
    # Import all internal functions
    foreach ($function in (Get-ChildItem "$ModuleRoot\internal\functions" -Filter "*.ps1" -Recurse -ErrorAction Ignore))
    {
        . Import-ModuleFile -Path $function.FullName
    }
    
    # Import all public functions
    foreach ($function in (Get-ChildItem "$ModuleRoot\functions" -Filter "*.ps1" -Recurse -ErrorAction Ignore))
    {
        . Import-ModuleFile -Path $function.FullName
    }
    
    # Execute Postimport actions
    foreach ($path in (& "$ModuleRoot\internal\scripts\postimport.ps1")) {
        . Import-ModuleFile -Path $path
    }
    
    # End it here, do not load compiled code below
    return
}
#endregion Load individual files

#region Load compiled code
<#
This file loads the strings documents from the respective language folders.
This allows localizing messages and errors.
Load psd1 language files for each language you wish to support.
Partial translations are acceptable - when missing a current language message,
it will fallback to English or another available language.
#>

Import-PSFLocalizedString -Path "$($script:ModuleRoot)\en-us\*.psd1" -Module 'PSDracoon' -Language 'en-US'

function Close-UploadChannel {
    <#
    .SYNOPSIS
    Closes Upload Channel which was opened before.
     
    .DESCRIPTION
    Closes Upload Channel which was opened before.
     
    .PARAMETER UploadUrl
    UploadURL which will be closed
     
    .EXAMPLE
    Close-UploadChannel -UploadUrl $UploadUrl
     
    Closes Uploadchannel with mandatory parameters.
    #>


    [CmdletBinding()]
    param (
        [Parameter(Mandatory = $true)]
        [String]
        $UploadUrl
    )
    
    $Parameter = @{
        "resolutionStrategy" = "overwrite"
    }

    try {
        $Response = Invoke-WebRequest -URI $UploadUrl -Method Put -ContentType "application/json"  -Body (convertTo-Json $Parameter) -ErrorAction Stop
        $File = ConvertFrom-Json $Response.content -ErrorAction Stop
    }
    catch {
        throw
    }

    $NodeID = $File.id
    Write-PSFMessage -Message "Die Datei wurde als neuer Knoten mit der ID $NodeID angelegt."

    $NodeID

}


function Get-Token
{
    <#
    .SYNOPSIS
    Requests a token from Dracoon API
     
    .DESCRIPTION
    Requests an authentication token by Calling Dracoon API (HTTP-Post)
     
    .PARAMETER ClientID
    Client ID of user
     
    .PARAMETER ClientSecret
    Client Secret of user
     
    .PARAMETER Credential
    User Credential
     
    .PARAMETER BaseURL
    URI of Dracoon Tenant
     
    .EXAMPLE
    Get-Token -ClientID $ClientId -ClientSecret $ClientSecret -Credential $Credential -BaseURL $BaseURL
 
    Receives token with mandatory parameters.
    #>

    [CmdletBinding()]
    param (
        [Parameter(Mandatory = $true)]
        [String]
        $ClientID,

        [Parameter(Mandatory = $true)]
        [String]
        $ClientSecret,

        [Parameter(Mandatory = $true)]
        [PSCredential]
        $Credential,

        [Parameter(Mandatory = $true)]
        [String]
        $BaseUrl

    )
    $TokenUrl = $BaseUrl + '/oauth/token'
    # Login über OAuth
    $Base64AuthInfo = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(("{0}:{1}" -f $ClientId,$ClientSecret)))
 
    $Body = @{
        "grant_type" = "password"
        "username" = $Credential.Username
        "password" = $Credential.GetNetworkCredential().Password
    }
    
    try {
        $Response = Invoke-WebRequest -URI $TokenUrl -Method Post -ContentType "application/x-www-form-urlencoded" -Body $Body -Headers @{Authorization=("Basic {0}" -f $Base64AuthInfo)} -ErrorAction Stop
    }
    catch {throw}

    [String]$Status = $response.StatusCode
    $Status = $Status.Remove(1,2)
    $Content = ConvertFrom-Json $Response.content
    $Token = $Content.access_token #Der Zugriffstoken, mit dem alle folgenden Aktionen auf DRACOON ausgeführt werden, wird in die Variable $Token gespeichert
    switch($status){
            
        1 {
            Write-PSFMessage -Message "HTTP Status: informational response – the request was received, continuing process"
        }
        2 {
            Write-PSFMessage -Message "HTTP Status: successful – the request was successfully received, understood, and accepted"
        }
        3 {
            Write-PSFMessage -Level Warning -Message "HTTP Status: redirection – further action needs to be taken in order to complete the request"
        }
        4 {
            Write-PSFMessage -Level Warning -Message "HTTP Status: client error – the request contains bad syntax or cannot be fulfilled"
        }
        5 {
            Write-PSFMessage -Level Warning -Message "HTTP Status: server error – the server failed to fulfil an apparently valid request"
        }
                      
        Default {
            Write-PSFMessage -Level Warning -Message "HTTP Status: UNKNOWN ERROR!"
        }
    }

    if (-not $Token){
        throw "no Token received"
    }
    
    $Token
}


function New-Password {
    <#
    .SYNOPSIS
    Password Generator
     
    .DESCRIPTION
    Password Generator
     
    .EXAMPLE
    New-Password
     
    Generates new password.
    #>

    [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseShouldProcessForStateChangingFunctions', '')]
    [CmdletBinding()]
    param (
    )
    $Alphabets = 'a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z'
    $numbers = 0..9
    $specialCharacters = "!,#,),+,@,_"
    $array = @()
    $array += $Alphabets.Split(',') | Get-Random -Count 4
    $array[0] = $array[0].ToUpper()
    $array[-1] = $array[-1].ToUpper()
    $array += $numbers | Get-Random -Count 3
    $array += $specialCharacters.Split(',') | Get-Random -Count 3
    return ($array | Get-Random -Count $array.Count) -join ""
}


function Open-UploadChannel
{
    <#
    .SYNOPSIS
    Opens Upload-Channel.
     
    .DESCRIPTION
    Opens Upload-Channel.
     
    .PARAMETER RoomID
    Online Space which will be used.
     
    .PARAMETER PDFName
    PDF which will be uploaded
     
    .PARAMETER APIUrl
    Base URL + "/api" -> Auto generated
     
    .PARAMETER Token
    Auth Token generated with Get-Token
     
    .EXAMPLE
    Open-UploadChannel -RoomID $RoomID -PDFName $PDFName -APIUrl $APIUrl -Token $Token
     
    Opens Uploadchannel with mandatory parameters.
    #>

    [CmdletBinding()]
    param (
        [Parameter(Mandatory = $true)]
        [String]
        $RoomID,

        [Parameter(Mandatory = $true)]
        [String]
        $PDFName,

        [Parameter(Mandatory = $true)]
        [String]
        $APIUrl,

        [Parameter(Mandatory = $true)]
        [String]
        $Token
    )
    $Parameter= @{
        "parentId" = $RoomID
        "name"     = $PDFName
    }
    $Response = $null
    $AccountUrl = $APIUrl + "/v4/nodes/files/uploads"
    try {
        $Response = Invoke-WebRequest -URI $AccountUrl -Method Post -ContentType "application/json" -Headers @{Authorization=("Bearer {0}" -f $Token)} -Body (convertTo-Json $Parameter) -ErrorAction Stop
    }
    catch {
        throw
    }

    $content = ConvertFrom-Json $Response.content
    
    [String]$Status = $response.StatusCode
    $Status = $Status.Remove(1,2)

    switch($status){
            
        1 {
            Write-PSFMessage -Message "HTTP Status: informational response – the request was received, continuing process"
        }
        2 {
            Write-PSFMessage -Message "HTTP Status: successful – the request was successfully received, understood, and accepted"
        }
        3 {
            Write-PSFMessage -Level Warning -Message "HTTP Status: redirection – further action needs to be taken in order to complete the request"
        }
        4 {
            Write-PSFMessage -Level Warning -Message "HTTP Status: client error – the request contains bad syntax or cannot be fulfilled"
        }
        5 {
            Write-PSFMessage -Level Warning -Message "HTTP Status: server error – the server failed to fulfil an apparently valid request"
        }
                      
        Default {
            Write-PSFMessage -Level Warning -Message "HTTP Status: UNKNOWN ERROR!"
        }
    }

    if (-not $content.uploadUrl){
        throw "No Upload-URL received"
    }

    $content.uploadUrl
   
}


function Send-DownloadLink
{
    <#
    .SYNOPSIS
    Shares uploaded file.
     
    .DESCRIPTION
    Uses New-Password for receiving random password.
    Sends Mail with sharelink to recipient.
    Send SMS with password to file to recipient.
     
    .PARAMETER APIUrl
    Base URL + "/api" -> Auto generated
     
    .PARAMETER Token
    Auth Token generated with Get-Token
     
    .PARAMETER Mobil
    Recipient mobile number imported from metadata
     
    .PARAMETER Mail
    Recipient mail imported from metadata.
     
    .PARAMETER NodeID
    NodeID generated after closing UploadChannel
     
    .EXAMPLE
    Send-DownloadLink -APIUrl $APIUrl -Token $Token -Mobil $Person.Mobil -Mail $person.Mail -NodeID $NodeID
     
    Sends DL-Link with mandatory parameters.
    #>

    [CmdletBinding()]
    param (
        [String]
        $APIUrl,
        
        [String]
        $Token,

        [String]
        $Mobil,

        [String]
        $Mail,

        [String]
        $NodeID
    )
    # Link und SMS
    $password = New-Password

    $parameter= @{
        showCreatorName = $true
        nodeId = $NodeID
        password = $password
        textMessageRecipients = @(
            $Mobil

        )
    }

    # Erstelle Sharelink und Sende SMS
    try {
        $Response = Invoke-WebRequest -URI "$APIUrl/v4/shares/downloads" -Method Post -ContentType "application/json" -Headers @{Authorization=("Bearer {0}" -f $Token)} -Body (ConvertTo-Json $parameter) -ErrorAction Stop
        $content = ConvertFrom-Json $Response.content -ErrorAction Stop
        $LinkID = $content.id
    }
    catch {
        throw
    }
    Write-PSFMessage -Message "Der im System erzeugte Downloadlink hat die ID $LinkID und ist mit dem Passwort $password geschützt."


    # Mailnotification
    try {
        $null = Invoke-WebRequest -URI "$APIUrl/v4/user/subscriptions/download_shares/$LinkID" -Method Post -ContentType "application/json" -Headers @{Authorization=("Bearer {0}" -f $Token)} -ErrorAction Stop
    }
    catch {
        throw
    }

      
    # Mailversand
    $Parameter= @{
        body = "Powered by DRACOON - Entwickelt von Philip Lorenz"
        recipients = @(
            $Mail
        )
    }

    $parameter = ConvertTo-Json -Depth 3 ($parameter)
    try {
        $null = Invoke-WebRequest -URI "$APIUrl/v4/shares/downloads/$LinkID/email" -Method Post -ContentType "application/json; charset=utf-8" -Headers @{Authorization=("Bearer {0}" -f $Token)} -Body $Parameter -ErrorAction Stop
    }
    catch {
        throw
    }
    Write-PSFMessage -Message "Es wurde eine Mail an $mail versendet."

}


function Send-File {
    <#
    .SYNOPSIS
    Uploads File.
     
    .DESCRIPTION
    Uploads File and checks whether file is available online afterwards.
     
    .PARAMETER File
    File which should be uploaded.
     
    .PARAMETER RoomID
    RoomID - Imported from standard config (Connect-Dracoon)
     
    .PARAMETER UploadURL
    Upload URL generated by Open-UploadChannel
     
    .EXAMPLE
    Send-File -File $PDF -RoomID $RoomID -UploadURL $uploadURL
 
    Uploads file with mandatory parameters.
 
    #>

    

    [CmdletBinding()]
    param (
        [Parameter(Mandatory = $true)]
        [System.IO.FileInfo]
        $File,

        [Parameter(Mandatory = $true)]
        [String]
        $RoomID,

        [Parameter(Mandatory = $true)]
        [String]
        $UploadURL
    )

    try {
        $null = Invoke-RestMethod $UploadUrl -ContentType "application/octet-stream" -Method Post -InFile $File.FullName -ErrorAction Stop
    }
    catch {
        throw
    }

    
    
    # Check, ob Datei vorhanden

    $parameter = @{
        "depth_level"   = "-1" #Bei der Einstellung -1 wird der ganze Ast ab der Stelle "parent_id" nach unten durchsucht
        "search_string" = $File.BaseName
        filter          = "type:eq:file"
        "parent_id"     = $RoomID #Das ist der Raum, in dem auf DRACOON die Testergebnisse abgelegt werden
    }

    $AccountUrl = $APIUrl + "/v4/nodes/search"
    try {
        $Response = Invoke-WebRequest -URI $AccountUrl -Method Get -ContentType "application/json" -Headers @{Authorization = ("Bearer {0}" -f $Token) } -Body $parameter -ErrorAction Stop
        $content = ConvertFrom-Json $Response.content -ErrorAction Stop
    }
    catch {
        throw
    }

    $inhalt = $content.items
    $status = @($inhalt).count

    switch ($status) {

        0 {
            Write-PSFMessage -Level Warning -Message "FEHLER: Dokument $($File.FullName) konnte nicht hochgeladen werden!!" -Target $File
            throw "FEHLER: Dokument $($File.FullName) konnte nicht hochgeladen werden!!"
        }
        1 {
            Write-PSFMessage -Message "Dokument $($File.FullName) wurde erfolgreich hochgeladen!" -Target $File
        }
        2 {
            Write-PSFMessage -Level Host -Message "Dokument $($File.FullName) liegt doppelt vor! Bitte prüfen" -Target $File
        }
        Default {
            Write-PSFMessage -Level Host -Message "Dokument $($File.FullName) liegt mehr als zwei mal vor! Bitte prüfen" -Target $File
        }
    }

}


function Connect-Dracoon
{
    <#
    .SYNOPSIS
    Saves config-data for PSDracoon (authentication details, etc.)
     
    .DESCRIPTION
    Tries to obtain Dracoon Authentication Token. If successful: Saves config-data for PSDracoon (authentication details, etc.)
     
    .PARAMETER BaseURL
    Tenant URI
     
    .PARAMETER Credential
    Authentication Credentials
     
    .PARAMETER ClientID
    ClientID (Generated within Dracoon Application)
     
    .PARAMETER ClientSecret
    ClientSecret (Generated within Dracoon Application)
     
    .PARAMETER RoomID
    RoomID: Defines Online Space
 
    .PARAMETER EnableException
    Exception Handling
     
    .EXAMPLE
    Connect-Dracoon -ClientID $ClientId -ClientSecret $ClientSecret -Credential $Credential -BaseURL $BaseURL
     
    Enrolls basic configuration.
    #>


    [CmdletBinding()]
    Param (
        [Parameter(Mandatory = $true)]
        [String]$BaseURL,

        [Parameter(Mandatory = $true)]
        [pscredential]$Credential,

        [Parameter(Mandatory = $true)]
        [String]$ClientID,

        [Parameter(Mandatory = $true)]
        [String]$ClientSecret,

        [Parameter(Mandatory = $true)]
        [String]$RoomID,

        [Switch]$EnableException
    )
    
    process
    {
        try {
            $null = Get-Token -ClientID $ClientId -ClientSecret $ClientSecret -Credential $Credential -BaseURL $BaseURL
        }
        catch {
            Stop-PSFFunction -Message "Anmeldung fehlgeschlagen! Bitte Zugangsdaten und Netzwerkverbindung prüfen!" -ErrorRecord $_ -Cmdlet $PSCmdlet -EnableException $EnableException
            return
        }

        Set-PSFConfig -Module 'PSDracoon' -Name 'BaseURL' -Value $BaseURL -PassThru | Register-PSFConfig
        Set-PSFConfig -Module 'PSDracoon' -Name 'Credential' -Value $Credential -PassThru | Register-PSFConfig
        Set-PSFConfig -Module 'PSDracoon' -Name 'ClientID' -Value $ClientID -PassThru | Register-PSFConfig
        Set-PSFConfig -Module 'PSDracoon' -Name 'ClientSecret' -Value $ClientSecret -PassThru | Register-PSFConfig
        Set-PSFConfig -Module 'PSDracoon' -Name 'RoomID' -Value $RoomID -PassThru | Register-PSFConfig
    
    }

}


function Publish-DracoonDocument {
    <#
    .SYNOPSIS
    Shares Dracoon Documents depending on Metadata file (Common UseCase: sharing test results)
     
    .DESCRIPTION
    Generates Path Variables (within standard directory: /%Appdata%/PSDracoon/):
        Ergebnisse: /%Appdata%/PSDracoon/Ergebnisse/
        Metadaten: /%Appdata%/PSDracoon/Metadaten/Metadaten.csv
        Report: /%Appdata%/PSDracoon/Report.csv
 
    begin:
    - Receives authentication token
    process:
    - Import PDF-List
    - Import Metafiles
    - Open UploadChannel
    - Upload File
    - Close UploadChannel
    - Sharing Link and password (Mail and SMS)
     
    .PARAMETER BaseURL
    BaseURL - Imported from standard config (Connect-Dracoon)
     
    .PARAMETER Credential
    Credential - Imported from standard config (Connect-Dracoon)
     
    .PARAMETER ClientID
    ClientID - Imported from standard config (Connect-Dracoon)
     
    .PARAMETER ClientSecret
    ClientSecret - Imported from standard config (Connect-Dracoon)
     
    .PARAMETER RoomID
    RoomID - Imported from standard config (Connect-Dracoon)
     
    .PARAMETER BasePath
    BasePath - Imported from standard config (Set within PSDracoon/internal/configurations/configuration.ps1)
     
    .PARAMETER EnableException
    Exception Handling
 
    .PARAMETER Confirm
    If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.
 
    .PARAMETER Whatif
    If this switch is enabled, no actions are performed but informational messages will be displayed that explain what would happen if the command were to run.
     
    .EXAMPLE
    Publish-DracoonDocument
 
    Uploads files.
    #>

    [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSReviewUnusedParameter', '')]
    [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseDeclaredVarsMoreThanAssignments', '')]
    [CmdletBinding(SupportsShouldProcess = $true)]
    Param (
        [String]$BaseURL = (Get-PSFConfigValue -FullName "PSDracoon.BaseURL"),

        [pscredential]$Credential = (Get-PSFConfigValue -FullName "PSDracoon.Credential"),

        [String]$ClientID = (Get-PSFConfigValue -FullName "PSDracoon.ClientID"),

        [String]$ClientSecret = (Get-PSFConfigValue -FullName "PSDracoon.ClientSecret"),

        [String]$RoomID = (Get-PSFConfigValue -FullName "PSDracoon.RoomID"),

        [String]$BasePath = (Get-PSFConfigValue -FullName "PSDracoon.BasePath"),

        [Switch]$EnableException
    )
    
    begin {

        $APIUrl = $BaseUrl + "/api"


        # Hier liegen die PDFs mit den Ergebnissen
        $ergebnisLocation = Join-Path -Path $BasePath -ChildPath "Ergebnisse"
        # CSV mit den Metadaten
        $Metadatendatei = Join-Path -Path $BasePath -ChildPath "Metadaten\Metadaten.csv"
        # Report-CSV
        $csvreport = Join-Path -Path $BasePath -ChildPath "Report.csv"


        
        # Abholen des AnmeldeTokens
        try {
            $token = Get-Token -ClientID $ClientId -ClientSecret $ClientSecret -Credential $Credential -BaseURL $BaseURL
        }
        catch {
            Stop-PSFFunction -Message "Beim Abholen des Tokens ist ein Fehler aufgetreten" -ErrorRecord $_ -Cmdlet $PSCmdlet -EnableException $EnableException
            return
        }
    }
    process {
        
        if (Test-PSFFunctionInterrupt) { return }

        # Import der PDF-Liste
        try {
            $PDFListe = Get-ChildItem -Path $ergebnisLocation -ErrorAction Stop
        }
        catch {
            Stop-PSFFunction -Message "Beim Abrufen der PDF-Liste ist ein Fehler aufgetreten" -ErrorRecord $_ -Cmdlet $PSCmdlet -EnableException $EnableException
            return
        }


        # Import der Metadaten
        try {
            $Metadata = Import-Csv -Path $Metadatendatei -Delimiter ";" -Encoding Default -ErrorAction Stop
        }
        catch {
            Stop-PSFFunction -Message "Beim Abrufen der Metadaten ist ein Fehler aufgetreten" -ErrorRecord $_ -Cmdlet $PSCmdlet -EnableException $EnableException
            return
        }

        # Zählvariable, die erfolgreich hochgeladene Files zählt
        $anzahl = 0

        # PDF-Freigabe für betroffene Personen
        foreach ($PDF in $PDFListe) {
            $PDFName = $PDF.BaseName
            $Person = $Metadata | Where-Object Testnummer -eq $PDFName
            if (-not $Person) {
                Stop-PSFFunction -Message "Person nicht gefunden für: $($PDF.FullName)" -Cmdlet $PSCmdlet -EnableException $EnableException -Continue
            }

            # Oeffnen des UploadChannels
            Invoke-PSFProtectedCommand -Action "Oeffne Upload-Channel" -Target $PDF -ScriptBlock {
                $uploadURL = Open-UploadChannel -RoomID $RoomID -PDFName $PDFName -APIUrl $APIUrl -Token $Token
            } -PSCmdlet $PSCmdlet -EnableException $EnableException -Continue

            # Uploaden des Falls
            Invoke-PSFProtectedCommand -Action "Lade Dokument hoch" -Target $PDF -ScriptBlock {
                Send-File -File $PDF -RoomID $RoomID -UploadURL $uploadURL
            } -PSCmdlet $PSCmdlet -EnableException $EnableException -Continue
            
            # Schließen des Upload Channels
            Invoke-PSFProtectedCommand -Action "Schliesse Upload-Channel" -Target $PDF -ScriptBlock {
                $NodeID = Close-UploadChannel -UploadURL $UploadUrl
            } -PSCmdlet $PSCmdlet -EnableException $EnableException -Continue

            # Erstellen eines teilbaren Links mit PW (und Mail- und SMSVersand)
            Invoke-PSFProtectedCommand -Action "Sende SMS und Mail" -Target $PDF -ScriptBlock {
                Send-DownloadLink -APIUrl $APIUrl -Token $Token -Mobil $Person.Mobil -Mail $person.Mail -NodeID $NodeID
            } -PSCmdlet $PSCmdlet -EnableException $EnableException -Continue

            $anzahl++
            

        }

        $report = [PSCustomObject]@{
            Datum        = get-date -Format dd/MM/yyyy
            Uhrzeit      = get-date -Format HH:mm:ss
            UploadAnzahl = $anzahl
        }

        if (-Not (Test-Path $csvreport)) {
            $report | export-csv -Path $csvreport
            Write-PSFMessage -Message "Report-CSV wurde erstellt"
        }
        else {
            $report | export-csv -Path $csvreport -Append
            Write-PSFMessage -Message "Report-CSV wurde ergänzt"
        }
    }

}


<#
This is an example configuration file
 
By default, it is enough to have a single one of them,
however if you have enough configuration settings to justify having multiple copies of it,
feel totally free to split them into multiple files.
#>


<#
# Example Configuration
Set-PSFConfig -Module 'PSDracoon' -Name 'Example.Setting' -Value 10 -Initialize -Validation 'integer' -Handler { } -Description "Example configuration setting. Your module can then use the setting using 'Get-PSFConfigValue'"
#>

Set-PSFConfig -Module 'PSDracoon' -Name 'BaseURL' -Value "" -Initialize -Validation 'String' -Description "Dracoon Tenant URL"
Set-PSFConfig -Module 'PSDracoon' -Name 'Credential' -Value $null -Initialize -Validation 'Credential' -Description "Credentials of requesting user"
Set-PSFConfig -Module 'PSDracoon' -Name 'ClientID' -Value "" -Initialize -Validation 'String' -Description "ClientID"
Set-PSFConfig -Module 'PSDracoon' -Name 'ClientSecret' -Value "" -Initialize -Validation 'String' -Description "ClientSecret"
Set-PSFConfig -Module 'PSDracoon' -Name 'RoomID' -Value "" -Initialize -Validation 'String' -Description "RoomID"
Set-PSFConfig -Module 'PSDracoon' -Name 'BasePath' -Value (Join-Path -Path (Get-PSFPath -Name AppData) -ChildPath "PSDracoon") -Initialize -Validation 'String' -Description "BasePath"



Set-PSFConfig -Module 'PSDracoon' -Name 'Import.DoDotSource' -Value $false -Initialize -Validation 'bool' -Description "Whether the module files should be dotsourced on import. By default, the files of this module are read as string value and invoked, which is faster but worse on debugging."
Set-PSFConfig -Module 'PSDracoon' -Name 'Import.IndividualFiles' -Value $false -Initialize -Validation 'bool' -Description "Whether the module files should be imported individually. During the module build, all module code is compiled into few files, which are imported instead by default. Loading the compiled versions is faster, using the individual files is easier for debugging and testing out adjustments."

<#
Stored scriptblocks are available in [PsfValidateScript()] attributes.
This makes it easier to centrally provide the same scriptblock multiple times,
without having to maintain it in separate locations.
 
It also prevents lengthy validation scriptblocks from making your parameter block
hard to read.
 
Set-PSFScriptblock -Name 'PSDracoon.ScriptBlockName' -Scriptblock {
     
}
#>


<#
# Example:
Register-PSFTeppScriptblock -Name "PSDracoon.alcohol" -ScriptBlock { 'Beer','Mead','Whiskey','Wine','Vodka','Rum (3y)', 'Rum (5y)', 'Rum (7y)' }
#>


<#
# Example:
Register-PSFTeppArgumentCompleter -Command Get-Alcohol -Parameter Type -Name PSDracoon.alcohol
#>


New-PSFLicense -Product 'PSDracoon' -Manufacturer '' -ProductVersion $script:ModuleVersion -ProductType Module -Name MIT -Version "1.0.0.0" -Date (Get-Date "2021-01-03") -Text @"
Copyright (c) 2021
 
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
 
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
 
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
"@

#endregion Load compiled code