commands.ps1

<#
.SYNOPSIS
Get the module URL
 
.DESCRIPTION
Gets the registered default URL that the module is using
 
.EXAMPLE
Get-PSNUrl
 
This will return a PSCustomObject containing the URL registered for the module
 
.NOTES
 
Author: M�tz Jensen (@Splaxi)
 
#>

function Get-PSNUrl {
    [CmdletBinding()]
    param (
    )
    
    end {
        [PSCustomObject]@{Url = (Get-PSFConfigValue -FullName "psnotification.url")}
    }
}

<#
.SYNOPSIS
Invoke a HTTP Endpoint
 
.DESCRIPTION
Invoke a HTTP Endpoint and send a payload along
 
.PARAMETER Url
The URL endpoint that is capable of handling your request
 
The URL parameter has a default value if you have configured one with the designated functions
 
.PARAMETER Payload
The raw (string) payload that you want to pass along to the HTTP Endpoint
 
.PARAMETER Type
Type parameter to instruct the HTTP Endpoint what kind of data that will be part of the request
 
.PARAMETER EnableException
This parameters disables user-friendly warnings and enables the throwing of exceptions.
This is less user friendly, but allows catching exceptions in calling scripts.
 
.EXAMPLE
$hashTable = @{email = "admin@domain.com"; subject = "More testing"; message = "I hope this finds you well"}
$payload = ($hashTable | ConvertTo-Json)
 
Invoke-PSNHttpEndpoint -Payload $payload -Url "https://prod-35.westeurope.logic.azure.com:443/workflows/14adfasdrae23354432636dsfasfdsaf/"
 
This will invoke the HTTP endpoint and send along a payload. The payload comes from the HashTable that is converted into a Json object.
 
.NOTES
 
Author: M�tz Jensen (@Splaxi)
 
#>

function Invoke-PSNHttpEndpoint {
    [CmdletBinding()]
    param (
        [string] $Url = (Get-PSNUrl).Url,

        [Parameter(Mandatory = $True)]
        [string] $Payload,

        [ValidateSet('Json')]
        [string] $Type = "Json",

        [switch] $EnableException
    )
    
    begin {
        if (-not $Url) {
            Write-PSFMessage -Level Warning -Message "It seems that you didn't pass a URL and the module doesn't have a configured one to use."
            Stop-PSFFunction -Message "Stopping because of missing URL" -EnableException $EnableException
            return
        }
    }
    
    process {
        if (Test-PSFFunctionInterrupt) {return}
        
        Write-PSFMessage -Level Verbose -Message "Prepping the details for executing the HTTP request."

        [System.Net.ServicePointManager]::SecurityProtocol = [System.Net.SecurityProtocolType]::Tls12;
        $request = [System.Net.WebRequest]::Create($Url)
        $request.Method = "POST"
        $request.ContentType = "application/$($Type.ToLower())";

        try {
            $stream = new-object System.IO.StreamWriter ($request.GetRequestStream())
            $stream.write($Payload)
            $stream.Flush()
            $stream.Close()

            Write-PSFMessage -Level Verbose -Message "Executing the HTTP request."
            $response = $request.GetResponse()
    
            $requestStream = $response.GetResponseStream()
            $readStream = New-Object System.IO.StreamReader $requestStream
            $data = $readStream.ReadToEnd()
        }
        catch {
            Write-PSFMessage -Level Verbose -Message "Something went wrong while contacting the http endpoint." -ErrorRecord $_
        }
        
        $data
    }
    
    end {
    }
}

<#
.SYNOPSIS
Send a notification message
 
.DESCRIPTION
Send a message styled notification
 
.PARAMETER Url
The URL endpoint that is capable of handling your request
 
.PARAMETER ReceiverEmail
The email address of the receiver that you want get the notification
 
.PARAMETER Subject
The subject of the notification that you want to send
 
.PARAMETER Message
The body/message of the notification that you want to send
 
.PARAMETER Json
The raw Json object that you want to pass
 
.PARAMETER AsJob
Switch to instruct the cmdlet to start a bacground job and make sure the execution isn't blocked while contacting the HTTP endpoint
 
.PARAMETER JobName
Name for the background job that will be started
 
.PARAMETER EnableException
This parameters disables user-friendly warnings and enables the throwing of exceptions.
This is less user friendly, but allows catching exceptions in calling scripts.
 
.EXAMPLE
Invoke-PSNMessage -ReceiverEmail "admin@domain.com" -Subject "Testing from the new module" -Message "This should arrive at your door steps" -Url "https://prod-35.westeurope.logic.azure.com:443/workflows/14adfasdrae23354432636dsfasfdsaf/"
 
This will invoke the HTTP endpoint and send of a notification styled message / payload. The notification will be sent to "admin@domain.com", with the Subject "Testing from the new module" and the Message "This should arrive at your door steps".
 
.EXAMPLE
$hashTable = @{email = "admin@domain.com"; subject = "More testing"; message = "I hope this finds you well"}
$payload = ($hashTable | ConvertTo-Json)
 
Invoke-PSNMessage -Json $payload -Url "https://prod-35.westeurope.logic.azure.com:443/workflows/14adfasdrae23354432636dsfasfdsaf/"
 
This will invoke the HTTP endpoint and send of a notification styled message / payload. The notification details comes from the HashTable that is converted into a Json object.
 
.EXAMPLE
Set-PSNUrl -Url "https://prod-35.westeurope.logic.azure.com:443/workflows/14adfasdrae23354432636dsfasfdsaf/"
Invoke-PSNMessage -ReceiverEmail "admin@domain.com" -Subject "Testing from the new module" -Message "This should arrive at your door steps"
 
This will invoke the default HTTP endpoint that has been configured for the module and send of a notification styled message / payload. The notification will be sent to "admin@domain.com", with the Subject "Testing from the new module" and the Message "This should arrive at your door steps".
 
.EXAMPLE
Invoke-PSNMessage -ReceiverEmail "admin@domain.com" -Subject "Testing from the new module" -Message "This should arrive at your door steps" -AsJob
 
This will invoke the default HTTP endpoint that has been configured for the module and send of a notification styled message / payload. The notification will be sent to "admin@domain.com", with the Subject "Testing from the new module" and the Message "This should arrive at your door steps". The execution is done in a background job and will not block the execution.
 
.NOTES
 
Author: M�tz Jensen (@Splaxi)
 
#>

function Invoke-PSNMessage {
    [CmdletBinding(DefaultParameterSetName = 'Specific')]
    param (
        [string] $Url = (Get-PSNUrl).Url,

        [Parameter(Mandatory = $True, ParameterSetName = 'Specific')]
        [Alias('Email')]
        [string] $ReceiverEmail,

        [Parameter(Mandatory = $True, ParameterSetName = 'Specific')]
        [string] $Subject,

        [Parameter(Mandatory = $True, ParameterSetName = 'Specific')]
        [string] $Message,

        [Parameter(Mandatory = $True, ParameterSetName = 'Json')]
        [Alias('Payload')]
        [string] $Json,

        [switch] $AsJob,

        [string] $JobName = "HttpEndpointInvocation",

        [switch] $EnableException

    )

    begin {
        if(-not $Url) {
            Write-PSFMessage -Level Warning -Message "It seems that you didn't pass a URL and the module doesn't have a configured one to use."
            Stop-PSFFunction -Message "Stopping because of missing URL" -EnableException $EnableException
            return
        }

    }
    
    process {
        if(Test-PSFFunctionInterrupt) {return}

        if ($PSCmdlet.ParameterSetName -eq "Json") {
            Write-PSFMessage -Level Verbose -Message "The execution is a Json payload passed directly."
            $RequestData = $Json
        }
        else {
            Write-PSFMessage -Level Verbose -Message "The execution is a specific parameters passed."
            $RequestData = "{`"email`":`"$ReceiverEmail`", `"message`":`"$Message`", `"subject`":`"$Subject`"}"
        }
        
        if($AsJob.IsPresent) {
            $Arguments  = @{Url = $Url; Payload = $RequestData}
            Start-RSJob -Name $JobName -ScriptBlock {
                param($Parameters)
                Import-Module PSNotification -Force -PassThru
                Invoke-PSNHttpEndpoint @Parameters
             } -ArgumentList $Arguments
        }
        else {
            Invoke-PSNHttpEndpoint -Url $Url -Payload $RequestData
        }
    }
    
    end {
    }
}


<#
.SYNOPSIS
Set the URL for the module
 
.DESCRIPTION
Register the default URL that the module should be using
 
.PARAMETER Url
URL of the HTTP Endpoint that you want the module to invoke
 
.PARAMETER Temporary
Switch to instruct the cmdlet NOT to store the URL in the persisted storage for the module
 
.EXAMPLE
Set-PSNUrl -Url "https://prod-35.westeurope.logic.azure.com:443/workflows/14adfasdrae23354432636dsfasfdsaf/"
 
This will set the default URL for the module to "https://prod-35.westeurope.logic.azure.com:443/workflows/14adfasdrae23354432636dsfasfdsaf/"
 
.NOTES
 
Author: M�tz Jensen (@Splaxi)
 
#>

function Set-PSNUrl {
    [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSUseShouldProcessForStateChangingFunctions", "")]
    [CmdletBinding()]
    param (
        [Parameter(Mandatory = $true)]
        [string] $Url,

        [switch] $Temporary
    )
    
    end {
        Set-PSFConfig -FullName "psnotification.url" -Value $Url

        if (-not $Temporary) {
            Get-PSFConfig -FullName "psnotification.url" | Register-PSFConfig
    
            Write-PSFMessage -Level Verbose -Message "The URL has been configured and registered."
        }
    }
}