FastTrack-ConfigurationManagement.psm1

Add-Type -AssemblyName System.Web -ErrorAction SilentlyContinue
Function Get-ResponseError {
    param([System.Net.HttpWebResponse]$Response)
    $streamReader = New-Object System.IO.StreamReader($Response.GetResponseStream())
    $streamReader.BaseStream.Position = 0
    $streamReader.DiscardBufferedData()
    $body = ConvertFrom-Json($streamReader.ReadToEnd())
    Add-Member -InputObject $body -MemberType NoteProperty -Name "StatusCode" -Value $_.Exception.Response.StatusCode
    $body
}
Function Invoke-GetRequest {
    param([String]$Uri, [hashtable]$Headers)
    $response = try {
        Invoke-RestMethod -Method GET -Uri $Uri -ContentType 'application/json' -Headers $Headers
    } catch {
        Get-ResponseError $_.Exception.Response
    }

    return $response
}
Function Invoke-PostRequest {
    param([String]$Uri, [hashtable]$Headers, [String]$Body)
    $response = try {
    Invoke-RestMethod -Method POST -Uri $Uri -ContentType 'application/json' -Headers $Headers -Body $Body
    } catch {
    Get-ResponseError $_.Exception.Response
    }

    return $response
}
Function Invoke-PutRequest {
    param([String]$Uri, [hashtable]$Headers, [String]$Body)
    $response = try {
    Invoke-RestMethod -Method PUT -Uri $Uri -ContentType 'application/json' -Headers $Headers -Body $Body
    } catch {
    Get-ResponseError $_.Exception.Response
    }

    return $response
}
Function Invoke-DeleteRequest {
    param([String]$Uri, [hashtable]$Headers, [String]$Body)
    $response = try {
    Invoke-RestMethod -Method DELETE -Uri $Uri -ContentType 'application/json' -Headers $Headers -Body $Body
    } catch {
    Get-ResponseError $_.Exception.Response
    }

    return $response
}

Function SetBaseRecipientValues {
    param
    (
        [string] $FirstName,
        [string] $LastName,
        [string] $EmailAddress
    )

    $Recipient = (New-Object PSObject |
        Add-Member -PassThru NoteProperty FirstName $FirstName |
        Add-Member -PassThru NoteProperty LastName $LastName |
        Add-Member -PassThru NoteProperty EmailAddress $EmailAddress)

    return $Recipient
}

Function SetIdentityRecipientValues {

    [string] $TenantID =  $global:MsoAdminProperties['MSO-CompanyTenantInfo']
    [string] $CompanyName = $global:MsoAdminProperties["MSO-CompanyInfo"].DisplayName 
    [string] $LogonUserEmail = $global:MsoAdminProperties["MSO-LoggedOnUser"].Account

    $Identity = (New-Object PSObject |
        Add-Member -PassThru NoteProperty TenantId $TenantID |
        Add-Member -PassThru NoteProperty CompanyName $CompanyName |
        Add-Member -PassThru NoteProperty LogonUserEmail $LogonUserEmail)

    return $Identity
}

Function SetCreateRequestValues{
    param
    (
        [string] $FirstName,
        [string] $LastName,
        [string] $EmailAddress
    )

        $CustomerIdentity =  SetIdentityRecipientValues

        $Recipient = (New-Object PSObject |
                        Add-Member -PassThru NoteProperty FirstName $FirstName |
                        Add-Member -PassThru NoteProperty LastName $LastName |
                        Add-Member -PassThru NoteProperty EmailAddress $EmailAddress)

        $RecipientArray = @()
        $RecipientArray += $Recipient

        $CustomerObject = (New-Object PSObject |
        Add-Member -PassThru NoteProperty Identity $CustomerIdentity |
        Add-Member -PassThru NoteProperty Recipient $RecipientArray)

        return $CustomerObject
}

Function SetUpdateRequestValues{
    param
    (
        [string] $FirstName,
        [string] $LastName,
        [string] $EmailAddress
    )

        $CustomerIdentity = SetIdentityRecipientValues

        $CustomerObject = (New-Object PSObject |
        Add-Member -PassThru NoteProperty Identity $CustomerIdentity |
        Add-Member -PassThru NoteProperty FirstName $FirstName |
        Add-Member -PassThru NoteProperty LastName $LastName |
        Add-Member -PassThru NoteProperty EmailAddress $EmailAddress)

        return $CustomerObject
}

function Get-FastTrackConfiguration {
<#
.SYNOPSIS
    Get Customer Configuration List
.DESCRIPTION
    This cmdlet is intended for customers who are Global Administrators to get all the customer configuration details.
 
    In order to use this cmdlet, you must first login using the Login-FastTrackAcount cmdlet.
.PARAMETER EnvironmentMode
    DO NOT USE. INTERNAL USE ONLY
.EXAMPLE
    Get-FastTrackConfiguration
.INPUTS
    None
.OUTPUTS
    System.Management.Automation.PSObject
        This cmdlet generates a System.Management.Automation.PSObject object that represents the list of Customer configuration Details.
.LINK
    New-FastTrackConfiguration
    Set-FastTrackConfiguration
    Remove-FastTrackConfiguration
#>

    param(
            [Parameter(Mandatory=$false,ValueFromPipeline=$true)]
            [ValidateSet("dev","uat","prod")]
            [string] $EnvironmentMode = "prod"
        )

    if($global:MsoAdminProperties.Count -eq 0)
    {
        Write-Warning "Unable to retrieve Office 365 credentials! :: Please call [Login-FastTrackAccount] function."
        return    
    }

    [string]$CustomerId = $global:MsoAdminProperties["MSO-CompanyTenantInfo"]
    Write-Host "Tenent id- $CustomerId selected."

    $header = @{}
    $header.Add("ACCESS_TOKEN",$global:MsftAccessToken)
    $header.Add("TENANT_ID",$global:MsoAdminProperties["MSO-CompanyTenantInfo"])
    Write-Host "Sending Configuration List Request..."

    if($EnvironmentMode.Equals("UAT", [System.StringComparison]::CurrentCultureIgnoreCase))
    {
        $JsonResult = Invoke-GetRequest -Uri ([System.String]::Format("https://msft-csi-{0}.azurewebsites.net/api/{1}/Recipient",$EnvironmentMode,$CustomerId)) -Headers $header 
    }
    else
    {
        $JsonResult = Invoke-GetRequest -Uri ([System.String]::Format("https://msft-cssp-{0}.azurewebsites.net/api/{1}/Recipient",$EnvironmentMode,$CustomerId)) -Headers $header 
    }

    if($JsonResult.StatusCode -ne $null)
    {
        Write-Warning "Request failed! : $($JsonResult.StatusCode) - Error Message: $($JsonResult)"
    }
    else
    {
        Write-Host "Get request completed"
    }
    
    return $JsonResult
}

function New-FastTrackConfiguration {
<#
.SYNOPSIS
    Creates an new Customer Configuration
.DESCRIPTION
    This cmdlet is intended for customers who are Global Administrators to create a new customer configuration
 
    In order to use this cmdlet, you must first login using the Login-FastTrackAcount cmdlet.
.PARAMETER FirstName
    First Name of the customer
.PARAMETER LastName
    Last Name of the customer
.PARAMETER EmailAddress
    Email Address of the customer
.PARAMETER EnvironmentMode
    DO NOT USE. INTERNAL USE ONLY
.EXAMPLE
     New-FastTrackConfiguration -FirstName "abc" -LastName "xyz" -EmailAddress "pattif@contoso.net"
.INPUTS
    System.String
.OUTPUTS
    System.Management.Automation.PSObject
        This cmdlet generates a System.Management.Automation.PSObject object that represents the Transaction ID .
.LINK
    Get-FastTrackConfiguration
    Set-FastTrackConfiguration
    Remove-FastTrackConfiguration
 
#>

    param(
            [Parameter(Mandatory=$true,ValueFromPipeline=$true)]
            [string] $FirstName,
            [Parameter(Mandatory=$true,ValueFromPipeline=$true)]
            [string] $LastName,
            [Parameter(Mandatory=$true,ValueFromPipeline=$true)]
            [string] $EmailAddress,
            [Parameter(Mandatory=$false,ValueFromPipeline=$true)]
            [ValidateSet("dev","uat","prod")]
            [string] $EnvironmentMode = "prod"
        )

    if($global:MsoAdminProperties.Count -eq 0)
    {
        Write-Warning "Unable to retrieve Office 365 credentials! :: Please call [Login-FastTrackAccount] function."
        return    
    }

    $jsonObj = SetCreateRequestValues -FirstName: $FirstName `
                                -LastName: $LastName `
                                -EmailAddress: $EmailAddress

    $serializedJson = $jsonObj | ConvertTo-Json -Compress: $true
    $header = @{}
    $header.Add("ACCESS_TOKEN",$global:MsftAccessToken)
    $header.Add("TENANT_ID",$global:MsoAdminProperties["MSO-CompanyTenantInfo"])
    Write-Host "Sending Configuration Create Request..."
    if($EnvironmentMode.Equals("UAT", [System.StringComparison]::CurrentCultureIgnoreCase))
    {
        $JsonResult = Invoke-PostRequest -Uri ([System.String]::Format("https://msft-csi-{0}.azurewebsites.net/api/Recipient/Create",$EnvironmentMode)) -Headers $header -Body $serializedJson
    }
    else
    {
        $JsonResult = Invoke-PostRequest -Uri ([System.String]::Format("https://msft-cssp-{0}.azurewebsites.net/api/Recipient/Create",$EnvironmentMode)) -Headers $header -Body $serializedJson
    }
            
    if($JsonResult.StatusCode -ne $null)
    {
        Write-Warning "Request failed! : $($JsonResult.StatusCode) - Error Message: $($JsonResult)"
    }
    else
    {
        Write-Host "Request Generated Transaction ID $($JsonResult.TransactionId)"
    }
    
    return $JsonResult

}
function Set-FastTrackConfiguration {
<#
.SYNOPSIS
    Updates Customer Configuration
.DESCRIPTION
    This cmdlet is intended for customers who are Global Administrators to update an existing customer configuration.
 
    In order to use this cmdlet, you must first login using the Login-FastTrackAcount cmdlet.
.PARAMETER RecipientId
    An unique GUID that identifies a specific customer configuration.
.PARAMETER FirstName
    First Name of the customer.
.PARAMETER LastName
    Last Name of the customer.
.PARAMETER EmailAddress
    Email Address of the customer
.PARAMETER EnvironmentMode
    DO NOT USE. INTERNAL USE ONLY
.EXAMPLE
    Set-FastTrackConfiguration -RecipientId "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx" -FirstName "abc" -LastName "xyz" -EmailAddress "pattif@contoso.net"
.INPUTS
    System.String
.OUTPUTS
    System.Management.Automation.PSObject
        This cmdlet generates a System.Management.Automation.PSObject object that represents the Transaction ID .
.LINK
    Get-FastTrackConfiguration
    New-FastTrackConfiguration
    Remove-FastTrackConfiguration
#>

    param(
            [Parameter(Mandatory=$true,ValueFromPipeline=$true)]
            [string] $RecipientId,
            [Parameter(Mandatory=$true,ValueFromPipeline=$true)]
            [string] $FirstName,
            [Parameter(Mandatory=$true,ValueFromPipeline=$true)]
            [string] $LastName,
            [Parameter(Mandatory=$true,ValueFromPipeline=$true)]
            [string] $UserEmail,
            [Parameter(Mandatory=$false,ValueFromPipeline=$true)]
            [ValidateSet("dev","uat","prod")]
            [string] $EnvironmentMode = "prod"
        )

    if($global:MsoAdminProperties.Count -eq 0)
    {
        Write-Warning "Unable to retrieve Office 365 credentials! :: Please call [Login-FastTrackAccount] function."
        return    
    }


    $jsonObj = SetUpdateRequestValues -RecipientId $RecipientId -FirstName $FirstName -LastName $LastName -EmailAddress $UserEmail

    $serializedJson = $jsonObj | ConvertTo-Json -Compress: $true
    write-host $serializedJson

    $header = @{}
    $header.Add("ACCESS_TOKEN",$global:MsftAccessToken)
    $header.Add("TENANT_ID",$global:MsoAdminProperties["MSO-CompanyTenantInfo"])
    Write-Host "Sending Configuration Update Request..."
    if($EnvironmentMode.Equals("UAT", [System.StringComparison]::CurrentCultureIgnoreCase))
    {
        $JsonResult = Invoke-PutRequest -Uri ([System.String]::Format("https://msft-csi-{0}.azurewebsites.net/api/Recipient/{1}",$EnvironmentMode,$RecipientId)) -Headers $header -Body $serializedJson
    }
    else
    {
        $JsonResult = Invoke-PutRequest -Uri ([System.String]::Format("https://msft-cssp-{0}.azurewebsites.net/api/Recipient/{1}",$EnvironmentMode,$RecipientId)) -Headers $header -Body $serializedJson
    }
                
    if($JsonResult.StatusCode -ne $null)
    {
        Write-Warning "Request failed! : $($JsonResult.StatusCode) - Error Message: $($JsonResult)"
    }
    else
    {
        Write-Host "Request Generated Transaction ID"
    }
    
    return $JsonResult
}
function Remove-FastTrackConfiguration {
<#
.SYNOPSIS
    Removes a Customer Configuration
.DESCRIPTION
    This cmdlet is intended for customers who are Global Administrators to remove a specific customer configuration details.
 
    In order to use this cmdlet, you must first login using the Login-FastTrackAcount cmdlet.
.PARAMETER RecipientId
    An unique GUID that identifies a specific customer configuration.
.PARAMETER EnvironmentMode
    DO NOT USE. INTERNAL USE ONLY
.EXAMPLE
    Remove-FastTrackConfiguration -RecipientId "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"
.INPUTS
    System.String
.OUTPUTS
    System.Management.Automation.PSObject
        This cmdlet generates a System.Management.Automation.PSObject object that represents the Transaction ID .
.LINK
    New-FastTrackConfiguration
    Set-FastTrackConfiguration
    Get-FastTrackConfiguration
 
#>

       param(
                     [Parameter(Mandatory=$true,ValueFromPipeline=$true)]
                     [string] $RecipientId,
                     [Parameter(Mandatory=$false,ValueFromPipeline=$true)]
                     [ValidateSet("dev","uat","prod")]
                     [string] $EnvironmentMode = "prod"
              )

    if($global:MsoAdminProperties.Count -eq 0)
    {
        Write-Warning "Unable to retrieve Office 365 credentials! :: Please call [Login-FastTrackAccount] function."
        return    
    }
 
    $jsonObj = SetIdentityRecipientValues
    $serializedJson = $jsonObj | ConvertTo-Json -Compress: $true
    write-host $serializedJson

    $header = @{}
    $header.Add("ACCESS_TOKEN",$global:MsftAccessToken)
    $header.Add("TENANT_ID",$global:MsoAdminProperties["MSO-CompanyTenantInfo"])
    Write-Host "Sending Configuration Delete Request..."
    if($EnvironmentMode.Equals("UAT", [System.StringComparison]::CurrentCultureIgnoreCase))
    {
        $JsonResult = Invoke-DeleteRequest -Uri ([System.String]::Format("https://msft-csi-{0}.azurewebsites.net/api/Recipient/{1}", $EnvironmentMode, $RecipientId)) -Headers $header -Body $serializedJson
    }
    else
    {
        $JsonResult = Invoke-DeleteRequest -Uri ([System.String]::Format("https://msft-cssp-{0}.azurewebsites.net/api/Recipient/{1}", $EnvironmentMode, $RecipientId)) -Headers $header -Body $serializedJson
    }
            
    if($JsonResult.StatusCode -ne $null)
    {
        Write-Warning "Request failed! : $($JsonResult.StatusCode) - Error Message: $($JsonResult)"
    }
    else
    {
        Write-Host "Request Generated Transaction ID"
    }
       
       return $JsonResult     
}