Public/Push-ADUsersToBB.ps1

Function Push-ADUsersToBB {
    <#
    .SYNOPSIS
        Get user information from ActiveDirectory with the information needed in BrightBooking and process it directly in BrightBooking
    .DESCRIPTION
        Get user information via the Get-ADUser command, retreiving the information needed for BrightBooking. (Requiring RSAT tools: Remote Server Administration Tools)
    .PARAMETER Filter
        A filter used to pass to Get-ADUser, if you don't need a filter, then use: '*'
        Example: 'samAccountName -like "admin*"'
        More information: https://technet.microsoft.com/en-us/library/hh531527(v=ws.10).aspx
    .PARAMETER SearchBase
        A SearchBase used to pass to Get-ADUser, specifies an Active Directory path to search under.
        Example: "OU=Office,DC=Company,DC=com"
        More information: https://technet.microsoft.com/library/hh852208.aspx
    .PARAMETER Server
        Specifies the AD DS instance to connect to, by providing one of the following values for a corresponding domain name or directory server.
        More information: https://technet.microsoft.com/library/hh852208.aspx
    .PARAMETER ADUserPincodePropertyName
        Optional ActiveDirectory User Property which contains the pincode
    .PARAMETER ADUserNamePropertyName
        Optional ActiveDirectory User Property which contains the name of the user, in case you do not want to use the default property
    .PARAMETER ADSpecificUsername
        Optional way to get a specific username from ActiveDirectory which should be used to authenticate the users when he logs in into BrightBooking (app/portal). You can choose which username should be used, DOMAIN\UserName or the UserPrincipalName (UPN)
    .PARAMETER BrightBookingApiUrl
        Address of the BrightBooking API, e.g.: https://eu1.api.brightbooking.eu/
    .PARAMETER BrightBookingApiKey
        API key of the user to use to process the import
    .PARAMETER BrightBookingIntegrationName
        Name of the integration to link the users to
    .EXAMPLE
        Push-ADUsersToBB -Filter * -BrightBookingApiUrl "https://eu1.api.brightbooking.eu/" -BrightBookingApiKey "[your api key]" -BrightBookingIntegrationName "Office 365"
        # Get all users in the Active Directory and let BrightBooking process it directly
    .EXAMPLE
        Push-ADUsersToBB -Filter * -SearchBase "OU=Office,DC=Company,DC=com" -BrightBookingApiUrl "https://eu1.api.brightbooking.eu/" -BrightBookingApiKey "[your api key]" -BrightBookingIntegrationName "Office 365"
        # Get the users in the Active Directory, which are member of the given group and let BrightBooking process it directly
    .EXAMPLE
        Push-ADUsersToBB -Filter { memberOf -RecursiveMatch "CN=Administrators,DC=Company,DC=com" } -SearchBase "OU=Office,DC=Company,DC=com" -ADUserPincodePropertyName PersonnelNumber -BrightBookingApiUrl "https://eu1.api.brightbooking.eu/" -BrightBookingApiKey "[your api key]" -BrightBookingIntegrationName "Office 365"
        # Get the users in the Active Directory, which in the specified SearchBase path, and use the custom property 'PersonnelNumber' as pincode and let BrightBooking process it directly
    .LINK
        http://wiki.brightbooking.eu/
    .LINK
        https://technet.microsoft.com/library/hh852208.aspx
    .LINK
        Get-ADUsersForBB
    .LINK
        Convert-ADUsersToBBUserExport
    .LINK
        Export-ADUsersForBB
    #>


    [CmdletBinding()]
    Param(
      [Parameter(Mandatory=$True)]
       [string]$Filter,
   
      [Parameter(Mandatory=$False)]
       [string]$SearchBase,
      
      [Parameter(Mandatory=$False)]
       [string]$Server,

      [Parameter(Mandatory=$False)]
       [string]$ADUserPincodePropertyName,

      [Parameter(Mandatory=$False)]
       [string]$ADUserNamePropertyName,
       
      [Parameter(Mandatory=$False)]
       [string]$ADUserMobilePropertyName = "Mobile",
       
      [Parameter(Mandatory=$False)]
      [ValidateSet("None","UserPrincipalName","DomainPlusUsername")]
       [string]$ADSpecificUsername = "None",

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

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

      [Parameter(Mandatory=$True)]
       [string]$BrightBookingIntegrationName
    )

    Process {
        $ConvertUsersParams = @{
            ADSpecificUsername = $ADSpecificUsername
        }
        
        $ADUsersParams = @{
            Filter = $Filter
        }
        If ($SearchBase) {
            $ADUsersParams.SearchBase = $SearchBase
        }
        If ($Server) {    
            $ADUsersParams.Server = $Server
        }
        If ($ADUserPincodePropertyName) {
            $ADUsersParams.ADUserPincodePropertyName = $ADUserPincodePropertyName
            $ConvertUsersParams.ADUserPincodePropertyName = $ADUserPincodePropertyName
        }
        If ($ADUserNamePropertyName) {
            $ADUsersParams.ADUserNamePropertyName = $ADUserNamePropertyName
            $ConvertUsersParams.ADUserNamePropertyName = $ADUserNamePropertyName
        }
        If ($ADUserMobilePropertyName) {
            $ADUsersParams.ADUserMobilePropertyName = $ADUserMobilePropertyName
            $ConvertUsersParams.ADUserMobilePropertyName = $ADUserMobilePropertyName
        }

        # generate the csv file contents, generate to string
        $csvtext = Get-ADUsersForBB @ADUsersParams | Convert-ADUsersToBBUserExport @ConvertUsersParams | ConvertTo-Csv -NoTypeInformation | Out-String
        
        # convert the text so the encoding is correct to handle special characters
        $csvtext = [System.Text.Encoding]::UTF8.GetBytes($csvtext)        
        
        # post to the api
        $access_token = Get-BBAccessToken -BrightBookingApiUrl $BrightBookingApiUrl -BrightBookingApiKey $BrightBookingApiKey

        $resturi = [System.Uri]::new([System.Uri]::new($BrightBookingApiUrl), "/api/users/synchronize-direct-csv")                

        $QueryParameters = [System.Web.HttpUtility]::ParseQueryString([String]::Empty)
        $QueryParameters['integrationname'] = $BrightBookingIntegrationName
                
        $Request  = [System.UriBuilder]($resturi)
        $Request.Query = $QueryParameters.ToString()

        $body = $csvtext

        $hdrs = @{}
        $hdrs.Add("Authorization", "Bearer "+ $access_token)
        
        Try
        {
            $response = Invoke-WebRequest -Uri $Request.Uri -Method Post -Body $body -ContentType 'application/text' -Headers $hdrs
        
            If ($response.StatusCode -eq 200 -or $response.StatusCode -eq 201)
            {
                Write-Output "Finished synchronizing users to BrightBooking successfully"                
            }
        } 
        Catch 
        {
            $statusCode = $_.Exception.Response.StatusCode.Value__
            $responseText = $_

            Try
            {
                $jsonresponse = $responseText | ConvertFrom-Json
                If ($jsonresponse.SyncRoot)
                {
                    $statusMessage = $jsonresponse.SyncRoot
                }
                Else
                {
                    $statusMessage = $responseText
                }
            } 
            Catch 
            {
                $statusMessage = $responseText
            }

            throw "Synchronizing users to BrightBooking failed, probably because of invalid input, try to import the CSV manually (statuscode: $statusCode, message: $statusMessage)"
        }
    }
}