EasitGoWebservice.psm1

function Get-GOItems { 
      <#
      .SYNOPSIS
            Get data from BPS/GO with web services.
      .DESCRIPTION
            Connects to BPS/GO Web service with url, apikey and view and returns response as xml.
            If used with variable as in examples below, the following properties can be found as follows:

            Current page: $bpsdata.Envelope.Body.GetItemsResponse.page
            Total number of pages in response: $bpsdata.Envelope.Body.GetItemsResponse.totalNumberOfPages
            Total number of items in response: $bpsdata.Envelope.Body.GetItemsResponse.totalNumberOfItems
            Items: $bpsdata.Envelope.Body.GetItemsResponse.Items
            Details about fields used in view: $bpsdata.Envelope.Body.GetItemsResponse.Columns.Column

      .NOTES
            Copyright 2019 Easit AB

            Licensed under the Apache License, Version 2.0 (the "License");
            you may not use this file except in compliance with the License.
            You may obtain a copy of the License at

                http://www.apache.org/licenses/LICENSE-2.0

            Unless required by applicable law or agreed to in writing, software
            distributed under the License is distributed on an "AS IS" BASIS,
            WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
            See the License for the specific language governing permissions and
            limitations under the License.

      .LINK
            https://github.com/easitab/EasitGoWebservice/blob/master/EasitGoWebservice/Get-GOItems.ps1
      
      .EXAMPLE
            $bpsdata = Get-GOItems -url http://localhost/test/webservice/ -apikey 4745f62b7371c2aa5cb80be8cd56e6372f495f6g8c60494ek7f231548bb2a375 -view Incidents
      .EXAMPLE
            $bpsdata = Get-GOItems -url $url -apikey $api -view Incidents -page 1
      .EXAMPLE
            $bpsdata = Get-GOItems -url $url -apikey $api -view Incidents -page 1 -ColumnFilter 'Name,EQUALS,Extern organisation'
      .PARAMETER url
            Address to BPS/GO webservice. Default = http://localhost/webservice/
      .PARAMETER apikey
            API-key for BPS/GO.
      .PARAMETER importViewIdentifier
            View to get data from.
      .PARAMETER sortOrder
            Order in which to sort data, Descending or Ascending. Default = Descending
      .PARAMETER sortField
            Field to sort data with. Default = Id
      .PARAMETER viewPageNumber
            Used to get data from specific page in view. Each page contains 25 items. Default = 1.
      .PARAMETER ColumnFilter
            Used to filter data. Example: ColumnName,comparator,value
            Valid comparator: EQUALS, NOT_EQUALS, IN, NOT_IN, GREATER_THAN, GREATER_THAN_OR_EQUALS, LESS_THAN, LESS_THAN_OR_EQUALS, LIKE, NOT_LIKE
      .PARAMETER SSO
            Used if system is using SSO with IWA (Active Directory). Not need when using SAML2
      #>

      [CmdletBinding()]
      param ( 
            [parameter(Mandatory=$false)]
            [string] $url = "http://localhost/webservice/",

            [parameter(Mandatory=$true)]
            [Alias("api")]
            [string] $apikey,

            [parameter(Mandatory=$true)]
            [Alias("view")]
            [string] $importViewIdentifier,

            [parameter(Mandatory=$false)]
            [Alias("so")]
            [string] $sortOrder = "Descending",

            [parameter(Mandatory=$false)]
            [Alias("sf")]
            [string] $sortField = "Id",

            [parameter(Mandatory=$false)]
            [Alias("page")]
            [int] $viewPageNumber = 1,

            [parameter(Mandatory=$false)]
            [string[]] $ColumnFilter,

            [parameter(Mandatory=$false)]
            [switch] $SSO
      )
      ## TO DO
      # Remove all comments
      
      #$ivi = $importViewIdentifier
      #$so = $sortOrder
      #$sf = $sortField
      #$pc = $viewPageNumber

      Write-Verbose 'Setting authentication header'
      # basic authentucation
      $pair = "$($apikey): "
      $encodedCreds = [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes($pair))
      $basicAuthValue = "Basic $encodedCreds"
      Write-Verbose 'Authentication header set'

      Write-Verbose 'Creating payload'

      $payload = New-XMLforEasit -Get -ItemViewIdentifier "$importViewIdentifier" -SortOrder "$sortOrder" -SortField "$sortField" -Page "$viewPageNumber" -ColumnFilter "$ColumnFilter"


#$payload=@'
#<?xml version="1.0" encoding="utf-8"?>
#<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:sch="http://www.easit.com/bps/schemas">
# <soapenv:Header/>
# <soapenv:Body>
# <sch:GetItemsRequest>
# <sch:ItemViewIdentifier>$ivi</sch:ItemViewIdentifier>
# <sch:Page>$pc</sch:Page>
# <sch:SortColumn order="$so">$sf</sch:SortColumn>
# <!--<sch:ColumnFilter columnName="$cn" comparator="$comp">$cValue</sch:ColumnFilter>-->
# </sch:GetItemsRequest>
# </soapenv:Body>
#</soapenv:Envelope>
#'@
# Write-Verbose 'Payload created'
#
# Write-Verbose 'Replacing content in $payload with parameter input'
# try {
# $payload = $payload.Replace('$ivi', $ivi)
# $payload = $payload.Replace('$pc', $pc)
# $payload = $payload.Replace('$so', $so)
# $payload = $payload.Replace('$sf', $sf)
# if ($ColumnFilter) {
# $ColumnFilterArray = $ColumnFilter.Split(',')
# $ColumnFilterArray = $ColumnFilterArray.TrimStart()
# $payload = $payload.Replace('<!--', '')
# $payload = $payload.Replace('-->', '')
# $payload = $payload.Replace('$cn', $ColumnFilterArray[0])
# $payload = $payload.Replace('$comp', $ColumnFilterArray[1])
# $payload = $payload.Replace('$cValue', $ColumnFilterArray[2])
# Write-Verbose $payload
# }
# } catch {
# Write-Error 'Failed to update payload'
# Write-Error "$_"
# return
# }
# Write-Verbose 'Done replacing content in $payload with parameter input'

      #Write-Verbose 'Casting $payload as [xml]$SOAP'
      #[xml]$SOAP = $payload

      Write-Verbose 'Setting headers'
      # HTTP headers
      $headers = @{SOAPAction = ""; Authorization = $basicAuthValue}
      Write-Verbose 'Headers set'

      # Calling web service
      Write-Verbose 'Calling web service and using $SOAP as input for Body parameter'
      if ($SSO) {
            try {
                  Write-Verbose 'Using switch SSO. De facto UseDefaultCredentials for Invoke-WebRequest'
                  $r = Invoke-WebRequest -Uri $url -Method POST -ContentType 'text/xml' -Body $payload -Headers $headers -UseDefaultCredentials
                  Write-Verbose "Successfully connected to and got data from BPS"
            } catch {
                  Write-Error "Failed to connect to BPS!"
                  Write-Error "$_"
                  return $payload
            }
      } else {
            try {
                  $r = Invoke-WebRequest -Uri $url -Method POST -ContentType 'text/xml' -Body $payload -Headers $headers
                  Write-Verbose "Successfully connected to and got data from BPS"
            } catch {
                  Write-Error "Failed to connect to BPS!"
                  Write-Error "$_"
                  return $payload
            }
      }
      
      New-Variable -Name functionout
      [xml]$functionout = $r.Content
      Write-Verbose 'Casted content of reponse as [xml]$functionout'

      return $functionout
}
Export-ModuleMember -Function Get-GOItems
function Import-GOAssetItem {
      <#
      .SYNOPSIS
            Send data to BPS/GO with web services.
      .DESCRIPTION
            Update and create assets in Easit BPS/GO. Returns ID for asset in Easit BPS/GO.
            Specify 'ID' to update an existing asset.

      .NOTES
            Copyright 2019 Easit AB

            Licensed under the Apache License, Version 2.0 (the "License");
            you may not use this file except in compliance with the License.
            You may obtain a copy of the License at

                http://www.apache.org/licenses/LICENSE-2.0

            Unless required by applicable law or agreed to in writing, software
            distributed under the License is distributed on an "AS IS" BASIS,
            WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
            See the License for the specific language governing permissions and
            limitations under the License.

      .LINK
            https://github.com/easitab/EasitGoWebservice/blob/master/EasitGoWebservice/Import-GOAssetItem.ps1

      .EXAMPLE
            Import-GOAssetItem -url http://localhost/webservice/ -apikey a8d5eba7f4daa79ea6f1c17c6b453d17df9c27727610b142c70c51bb4eda3618 -ImportHandlerIdentifier CreateAssetGeneral -AssetName "Test" -SerialNumber "SN-467952" -Description "One general asset." -Status "Active" -Verbose -ShowDetails
      .EXAMPLE
            Import-GOAssetItem -url http://localhost/webservice/ -apikey a8d5eba7f4daa79ea6f1c17c6b453d17df9c27727610b142c70c51bb4eda3618 -ihi CreateAssetServer -AssetStartDate "2018-06-26" -InternalMemory "32" -HardriveSize "500" -Status "Active"
      .EXAMPLE
            Import-GOAssetItem -url http://localhost/webservice/ -api a8d5eba7f4daa79ea6f1c17c6b453d17df9c27727610b142c70c51bb4eda3618 -ImportHandlerIdentifier CreateAssetPC -ID "45" -OperatingSystem "Windows 10" -Status "Inactive"
      .EXAMPLE
            Import-GOAssetItem -url $url -apikey $api -ihi $identifier -ID "156" -Status "Inactive"
      .PARAMETER url
            Address to BPS/GO webservice. Default = http://localhost/webservice/
      .PARAMETER apikey
            API-key for BPS/GO.
      .PARAMETER ImportHandlerIdentifier
            ImportHandler to import data with. Default = CreateAssetGeneral
      .PARAMETER ID
            ID for asset in BPS/GO.
      .PARAMETER UID
            Unique ID for object during import. Default = 1.
      .PARAMETER AssetType
            Type of asset.
      .PARAMETER AssetInvoicingPeriod
            Invoicing period for asset.
      .PARAMETER AssetSupplierOrganizationID
            ID of organization to be set as supplier of asset.
      .PARAMETER Impact
            Impact of asset.
      .PARAMETER Manufacturer
            Manufacturer of asset.
      .PARAMETER OwnerContactID
            ID of contact to be set as owner of asset.
      .PARAMETER OwnerOrganizationID
            ID of organization to be set as owner of asset.
      .PARAMETER PriceListConnectionID
            ID of price list to connect with asset.
      .PARAMETER Status
            Status for asset.
      .PARAMETER CityLocation
            Location (City) of asset.
      .PARAMETER HouseLocation
            Location (House) of asset.
      .PARAMETER FinLifteTime
            Financial lifte time of asset.
      .PARAMETER LifeCycle
            Life cycle of asset.
      .PARAMETER ActivityDebit
            Activity debit for asset.
      .PARAMETER AssetName
            Name of asset.
      .PARAMETER AssetStartDate
            Contract start date for asset. Format = yyyy-MM-dd
      .PARAMETER BarCode
            Bar code for asset.
      .PARAMETER CIReference
            Reference ID for asset.
      .PARAMETER Description
            Description of asset.
      .PARAMETER FinancialNotes
            Financial notes for asset.
      .PARAMETER LastInventoryDate
            Last inventory date of asset. Format = yyyy-MM-dd
      .PARAMETER ObjectDebit
            Object debit for asset.
      .PARAMETER ProjectDebit
            Project debit for asset.
      .PARAMETER PurchaseDate
            Date of purchase of asset. Format = yyyy-MM-dd
      .PARAMETER PurchaseOrderNumber
            Purchase order number of asset.
      .PARAMETER PurchaseValueCurrency
            Purchase value of asset.
      .PARAMETER RoomLocation
            Location (Room) of asset.
      .PARAMETER SerialNumber
            Serial number for asset.
      .PARAMETER SupplierInvoiceId
            ID of invoice from supplier.
      .PARAMETER TheftId
            Theft ID for asset.
      .PARAMETER WarrantyExpireDate
            Date for when warranty of asset expires. Format = yyyy-MM-dd
      .PARAMETER ModelMonitor
            Model of monitor.
      .PARAMETER MonitorType
            Type of monitor.
      .PARAMETER MonitorSize
            Size of monitor.
      .PARAMETER MonitorResolution
            Resolution of monitor.
      .PARAMETER ConectionType_Monitor
            Conection type of monitor.
      .PARAMETER OperatingSystem
            Operating system for asset.
      .PARAMETER Equipment
            Equipment of asset.
      .PARAMETER ModelPC
            Model of PC/Computer.
      .PARAMETER ComputerType
            Type of PC/Computer.
      .PARAMETER HardriveSize
            Hardrive size of asset.
      .PARAMETER InternalMemory
            Internal memory of asset.
      .PARAMETER ProcessorSpeed
            Processor speed of asset.
      .PARAMETER SLA
            Service level agreement of asset. Valid values = true / false.
      .PARAMETER SLAExpiredate
            Expire date for SLA of asset. Format: yyyy-MM-dd
      .PARAMETER UserLogin
            Username of person using asset.
      .PARAMETER UserPassword
            Password for person using asset.
      .PARAMETER AssetPhoneModel
            Model of phone.
      .PARAMETER AssetPhoneType
            Type of phone.
      .PARAMETER Operator
            Operator for phone.
      .PARAMETER IMEINumber
            IMEI number of phone.
      .PARAMETER MobilePhoneNumber
            Mobile phone number.
      .PARAMETER PhoneNumber
            Phone number.
      .PARAMETER PukCode
            PUK code for phone.
      .PARAMETER ModelPrinter
            Model of printer.
      .PARAMETER IPAdress
            IP address to printer.
      .PARAMETER MacAddress
            Printer mac address.
      .PARAMETER NetworkName
            Printer network name.
      .PARAMETER ModelServer
            Model of server.
      .PARAMETER DNSName
            Server DNS name.
      .PARAMETER ServiceBlackout
            Notes about when service is undergoing maintenance.
      .PARAMETER Attachment
            Full path to file to be included in payload.
      .PARAMETER SSO
            Used if system is using SSO with IWA (Active Directory). Not need when using SAML2
      .PARAMETER ShowDetails
            If specified, the response, including ID, will be displayed to host.
      .PARAMETER dryRun
            If specified, payload will be save as payload_1.xml (or next available number) to your desktop instead of sent to BPS/GO.
            This parameter does not append, rewrite or remove any files from your desktop.
      #>

      [CmdletBinding()]
      param (
            [parameter(Mandatory=$false,ValueFromPipelineByPropertyName=$true)]
            [ValidateNotNullOrEmpty()]
            [Alias("uri")]
            [string] $url = "http://localhost/webservice/",

            [parameter(Mandatory=$true,ValueFromPipelineByPropertyName=$true)]
            [ValidateNotNullOrEmpty()]
            [Alias("api")]
            [string] $apikey,

            [parameter(Mandatory=$false,ValueFromPipelineByPropertyName=$true)]
            [ValidateNotNullOrEmpty()]
            [Alias("ihi")]
            [string] $ImportHandlerIdentifier = 'CreateAssetGeneral',

            [parameter(ParameterSetName='BPSAttribute',ValueFromPipelineByPropertyName=$true)]
            [int] $ID,

            [parameter(ParameterSetName='BPSAttribute',ValueFromPipelineByPropertyName=$true)]
            [Alias("Type")]
            [string] $AssetType,

            [parameter(ParameterSetName='BPSAttribute',ValueFromPipelineByPropertyName=$true)]
            [Alias("InvoicingPeriod")]
            [string] $AssetInvoicingPeriod,

            [parameter(ParameterSetName='BPSAttribute',ValueFromPipelineByPropertyName=$true)]
            [Alias("SupplierOrganizationID")]
            [int] $AssetSupplierOrganizationID,

            [parameter(ParameterSetName='BPSAttribute',ValueFromPipelineByPropertyName=$true)]
            [string] $Impact,

            [parameter(ParameterSetName='BPSAttribute',ValueFromPipelineByPropertyName=$true)]
            [string] $Manufacturer,

            [parameter(ParameterSetName='BPSAttribute',ValueFromPipelineByPropertyName=$true)]
            [Alias("OwnerContact")]
            [int] $OwnerContactID,

            [parameter(ParameterSetName='BPSAttribute',ValueFromPipelineByPropertyName=$true)]
            [Alias("OwnerOrganization")]
            [int] $OwnerOrganizationID,

            [parameter(ParameterSetName='BPSAttribute',ValueFromPipelineByPropertyName=$true)]
            [Alias("PriceListConnection","PriceList")]
            [int] $PriceListConnectionID,

            [parameter(ParameterSetName='BPSAttribute',ValueFromPipelineByPropertyName=$true)]
            [string] $Status,

            [parameter(ParameterSetName='BPSAttribute',ValueFromPipelineByPropertyName=$true)]
            [Alias("City")]
            [string] $CityLocation,

            [parameter(ParameterSetName='BPSAttribute',ValueFromPipelineByPropertyName=$true)]
            [Alias("House")]
            [string] $HouseLocation,

            [parameter(ParameterSetName='BPSAttribute',ValueFromPipelineByPropertyName=$true)]
            [string] $FinLifteTime,

            [parameter(ParameterSetName='BPSAttribute',ValueFromPipelineByPropertyName=$true)]
            [string] $LifeCycle,

            [parameter(ParameterSetName='BPSAttribute',ValueFromPipelineByPropertyName=$true)]
            [string] $ActivityDebit,

            [parameter(ParameterSetName='BPSAttribute',ValueFromPipelineByPropertyName=$true)]
            [Alias("Name")]
            [string] $AssetName,

            [parameter(ParameterSetName='BPSAttribute',ValueFromPipelineByPropertyName=$true)]
            [Alias("StartDate")]
            [string] $AssetStartDate,

            [parameter(ParameterSetName='BPSAttribute',ValueFromPipelineByPropertyName=$true)]
            [string] $BarCode,

            [parameter(ParameterSetName='BPSAttribute',ValueFromPipelineByPropertyName=$true)]
            [Alias("CI")]
            [string] $CIReference,

            [parameter(ParameterSetName='BPSAttribute',ValueFromPipelineByPropertyName=$true)]
            [string] $Description,

            [parameter(ParameterSetName='BPSAttribute',ValueFromPipelineByPropertyName=$true)]
            [string] $FinancialNotes,

            [parameter(ParameterSetName='BPSAttribute',ValueFromPipelineByPropertyName=$true)]
            [string] $LastInventoryDate,

            [parameter(ParameterSetName='BPSAttribute',ValueFromPipelineByPropertyName=$true)]
            [string] $ObjectDebit,

            [parameter(ParameterSetName='BPSAttribute',ValueFromPipelineByPropertyName=$true)]
            [string] $ProjectDebit,

            [parameter(ParameterSetName='BPSAttribute',ValueFromPipelineByPropertyName=$true)]
            [string] $PurchaseDate,

            [parameter(ParameterSetName='BPSAttribute',ValueFromPipelineByPropertyName=$true)]
            [string] $PurchaseOrderNumber,

            [parameter(ParameterSetName='BPSAttribute',ValueFromPipelineByPropertyName=$true)]
            [string] $PurchaseValueCurrency,

            [parameter(ParameterSetName='BPSAttribute',ValueFromPipelineByPropertyName=$true)]
            [string] $RoomLocation,

            [parameter(ParameterSetName='BPSAttribute',ValueFromPipelineByPropertyName=$true)]
            [string] $SerialNumber,

            [parameter(ParameterSetName='BPSAttribute',ValueFromPipelineByPropertyName=$true)]
            [string] $SupplierInvoiceId,

            [parameter(ParameterSetName='BPSAttribute',ValueFromPipelineByPropertyName=$true)]
            [string] $TheftId,

            [parameter(ParameterSetName='BPSAttribute',ValueFromPipelineByPropertyName=$true)]
            [string] $WarrantyExpireDate,

            [parameter(ParameterSetName='BPSAttribute',ValueFromPipelineByPropertyName=$true)]
            [string] $ModelMonitor,

            [parameter(ParameterSetName='BPSAttribute',ValueFromPipelineByPropertyName=$true)]
            [string] $MonitorType,

            [parameter(ParameterSetName='BPSAttribute',ValueFromPipelineByPropertyName=$true)]
            [string] $MonitorSize,

            [parameter(ParameterSetName='BPSAttribute',ValueFromPipelineByPropertyName=$true)]
            [string] $MonitorResolution,

            [parameter(ParameterSetName='BPSAttribute',ValueFromPipelineByPropertyName=$true)]
            [Alias("ConectionTypeMonitor")]
            [string] $ConectionType_Monitor,

            [parameter(ParameterSetName='BPSAttribute',ValueFromPipelineByPropertyName=$true)]
            [string] $OperatingSystem,

            [parameter(ParameterSetName='BPSAttribute',ValueFromPipelineByPropertyName=$true)]
            [string] $Equipment,

            [parameter(ParameterSetName='BPSAttribute',ValueFromPipelineByPropertyName=$true)]
            [string] $ModelPC,

            [parameter(ParameterSetName='BPSAttribute',ValueFromPipelineByPropertyName=$true)]
            [string] $ComputerType,

            [parameter(ParameterSetName='BPSAttribute',ValueFromPipelineByPropertyName=$true)]
            [int] $HardriveSize,

            [parameter(ParameterSetName='BPSAttribute',ValueFromPipelineByPropertyName=$true)]
            [int] $InternalMemory,

            [parameter(ParameterSetName='BPSAttribute',ValueFromPipelineByPropertyName=$true)]
            [string] $ProcessorSpeed,

            [parameter(ParameterSetName='BPSAttribute',ValueFromPipelineByPropertyName=$true)]
            [string] $SLA,

            [parameter(ParameterSetName='BPSAttribute',ValueFromPipelineByPropertyName=$true)]
            [string] $SLAExpiredate,

            [parameter(ParameterSetName='BPSAttribute',ValueFromPipelineByPropertyName=$true)]
            [string] $UserLogin,

            [parameter(ParameterSetName='BPSAttribute',ValueFromPipelineByPropertyName=$true)]
            [SecureString] $UserPassword,

            [parameter(ParameterSetName='BPSAttribute',ValueFromPipelineByPropertyName=$true)]
            [string] $AssetPhoneModel,

            [parameter(ParameterSetName='BPSAttribute',ValueFromPipelineByPropertyName=$true)]
            [string] $AssetPhoneType,

            [parameter(ParameterSetName='BPSAttribute',ValueFromPipelineByPropertyName=$true)]
            [string] $Operator,

            [parameter(ParameterSetName='BPSAttribute',ValueFromPipelineByPropertyName=$true)]
            [Alias("IMEI")]
            [string] $IMEINumber,

            [parameter(ParameterSetName='BPSAttribute',ValueFromPipelineByPropertyName=$true)]
            [string] $MobilePhoneNumber,

            [parameter(ParameterSetName='BPSAttribute',ValueFromPipelineByPropertyName=$true)]
            [string] $PhoneNumber,

            [parameter(ParameterSetName='BPSAttribute',ValueFromPipelineByPropertyName=$true)]
            [Alias("puk")]
            [string] $PukCode,

            [parameter(ParameterSetName='BPSAttribute',ValueFromPipelineByPropertyName=$true)]
            [string] $ModelPrinter,

            [parameter(ParameterSetName='BPSAttribute',ValueFromPipelineByPropertyName=$true)]
            [Alias("IP")]
            [string] $IPAdress,

            [parameter(ParameterSetName='BPSAttribute',ValueFromPipelineByPropertyName=$true)]
            [Alias("MAC")]
            [string] $MacAddress,

            [parameter(ParameterSetName='BPSAttribute',ValueFromPipelineByPropertyName=$true)]
            [string] $NetworkName,

            [parameter(ParameterSetName='BPSAttribute',ValueFromPipelineByPropertyName=$true)]
            [string] $ModelServer,

            [parameter(ParameterSetName='BPSAttribute',ValueFromPipelineByPropertyName=$true)]
            [string] $DNSName,

            [parameter(ParameterSetName='BPSAttribute',ValueFromPipelineByPropertyName=$true)]
            [string] $ServiceBlackout,

            [parameter(Mandatory=$false,ValueFromPipelineByPropertyName=$true)]
            [int] $uid = "1",

            [parameter(ParameterSetName='BPSAttribute',ValueFromPipelineByPropertyName=$true)]
            [Alias("File")]
            [string] $Attachment,

            [parameter(Mandatory=$false)]
            [switch] $SSO,

            [parameter(Mandatory=$false)]
            [switch] $dryRun,

            [parameter(Mandatory=$false)]
            [switch] $ShowDetails
      )

      try {
            Write-Verbose "Collecting list of used parameters"
            $CommandName = $PSCmdlet.MyInvocation.InvocationName
            $ParameterList = (Get-Command -Name $commandName).Parameters.Values
            Write-Verbose "Successfully collected list of used parameters"
      } catch {
            Write-Error 'Failed to get list of used parameters!'
            Write-Error "$_"
            break
      }

      Write-Verbose "Starting loop for creating hashtable of parameter..."
      $params = [ordered]@{}
      foreach ($parameter in $parameterList) {
            Write-Verbose "Starting loop for $($parameter.Name)"
            $ParameterSetToMatch = 'BPSAttribute'
            $parameterSets = $parameter.ParameterSets.Keys
            if ($parameterSets -contains $ParameterSetToMatch) {
                  Write-Verbose "$($parameter.Name) is part of BPS parameter set"
                  $parDetails = Get-Variable -Name $parameter.Name
                  if ($parDetails.Value) {
                        Write-Verbose "$($parameter.Name) have a value"
                        $parName = $parDetails.Name
                        $parValue = $parDetails.Value
                        $params.Add("$parName", "$parValue")
                  } else {
                        Write-Verbose "$($parameter.Name) does not have a value!"
                  }
            } else {
                  Write-Verbose "$($parameter.Name) is not part of BPS parameter set!"
            } Write-Verbose "Loop for $($parameter.Name) reached end!"
      }
      Write-Verbose "Successfully created hashtable of parameter!"
      $payload = New-XMLforEasit -Import -ImportHandlerIdentifier "$ImportHandlerIdentifier" -Params $Params

      if ($dryRun) {
            Write-Verbose "dryRun specified! Trying to save payload to file instead of sending it to BPS"
            $i = 1
            $currentUserProfile = [Environment]::GetEnvironmentVariable("USERPROFILE")
            $userProfileDesktop = "$currentUserProfile\Desktop"
            do {
                  $outputFileName = "payload_$i.xml"
                  if (Test-Path $userProfileDesktop\$outputFileName) {
                        $i++
                        Write-Host "$i"
                  }
            } until (!(Test-Path $userProfileDesktop\$outputFileName))
            if (!(Test-Path $userProfileDesktop\$outputFileName)) {
                  try {
                        $outputFileName = "payload_$i.xml"
                        $payload.Save("$userProfileDesktop\$outputFileName")
                        Write-Verbose "Saved payload to file, will now end!"
                        break
                  } catch {
                        Write-Error "Unable to save payload to file!"
                        Write-Error "$_"
                        break
                  }
            }
      }

      Write-Verbose "Creating header for web request!"
      try {
            $pair = "$($apikey): "
            $encodedCreds = [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes($pair))
            $basicAuthValue = "Basic $encodedCreds"
            $headers = @{SOAPAction = ""; Authorization = $basicAuthValue}
            Write-Verbose "Header created for web request!"
      } catch {
            Write-Error "Failed to create header!"
            Write-Error "$_"
            break
      }
      Write-Verbose "Calling web service and using payload as input for Body parameter"
      if ($SSO) {
            try {
                  Write-Verbose 'Using switch SSO. De facto UseDefaultCredentials for Invoke-WebRequest'
                  $r = Invoke-WebRequest -Uri $url -Method POST -ContentType 'text/xml' -Body $payload -Headers $headers -UseDefaultCredentials
                  Write-Verbose "Successfully connected to and imported data to BPS"
            } catch {
                  Write-Error "Failed to connect to BPS!"
                  Write-Error "$_"
                  return $payload
            }
      } else {
            try {
                  $r = Invoke-WebRequest -Uri $url -Method POST -ContentType 'text/xml' -Body $payload -Headers $headers
                  Write-Verbose "Successfully connected to and imported data to BPS"
            } catch {
                  Write-Error "Failed to connect to BPS!"
                  Write-Error "$_"
                  return $payload
            }
      }
      
      New-Variable -Name functionout
      [xml]$functionout = $r.Content
      Write-Verbose 'Casted content of reponse as [xml]$functionout'

      if ($ShowDetails) {
            $responseResult = $functionout.Envelope.Body.ImportItemsResponse.ImportItemResult.result
            $responseID = $functionout.Envelope.Body.ImportItemsResponse.ImportItemResult.ReturnValues.ReturnValue.InnerXml
            Write-Host "Result: $responseResult"
            Write-Host "ID for created item: $responseID"
      }
      Write-Verbose "Function complete!"
}
Export-ModuleMember -Function Import-GOAssetItem
function Import-GOContactItem {
      <#
      .SYNOPSIS
            Send data to BPS/GO with web services.
      .DESCRIPTION
            Update and create contacts in Easit BPS/GO. Returns ID for item in Easit BPS/GO.
            Specify 'ID' to update an existing contact.

      .NOTES
            Copyright 2019 Easit AB

            Licensed under the Apache License, Version 2.0 (the "License");
            you may not use this file except in compliance with the License.
            You may obtain a copy of the License at

                http://www.apache.org/licenses/LICENSE-2.0

            Unless required by applicable law or agreed to in writing, software
            distributed under the License is distributed on an "AS IS" BASIS,
            WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
            See the License for the specific language governing permissions and
            limitations under the License.

      .LINK
            https://github.com/easitab/EasitGoWebservice/blob/master/EasitGoWebservice/Import-GOContactItem.ps1

      .EXAMPLE
            Import-GOContactItem -url http://localhost/webservice/ -apikey a8d5eba7f4daa79ea6f1c17c6b453d17df9c27727610b142c70c51bb4eda3618 -ImportHandlerIdentifier CreateContact -OrganizationID "12" -Position "Manager" -Deparment "Support" -FirstName "Test" -Surname "Testsson" -Username "te12te" -SecId "97584621" -Verbose -ShowDetails
      .EXAMPLE
            Import-GOContactItem -url http://localhost/webservice/ -apikey a8d5eba7f4daa79ea6f1c17c6b453d17df9c27727610b142c70c51bb4eda3618 -ihi CreateContact -ID "649" -Inactive "true"
      .EXAMPLE
            Import-GOContactItem -url http://localhost/webservice/ -api a8d5eba7f4daa79ea6f1c17c6b453d17df9c27727610b142c70c51bb4eda3618 -ImportHandlerIdentifier CreateContact -ID "649" -Surname "Andersson" -Email "test.anders@company.com" -FQDN "$FQDN"
      .EXAMPLE
            Import-GOContactItem -url $url -apikey $api -ihi $identifier -ID "156" -Inactive "false" -Responsible_Manager "true"
      .PARAMETER url
            Address to BPS/GO webservice. Default = http://localhost/webservice/
      .PARAMETER apikey
            API-key for BPS/GO.
      .PARAMETER ImportHandlerIdentifier
            ImportHandler to import data with. Default = CreateContact
      .PARAMETER ID
            ID for contact in BPS/GO.
      .PARAMETER FirstName
            First name of contact in BPS/GO.
      .PARAMETER Surname
            Last name of contact in BPS/GO.
      .PARAMETER OrganizationID
            ID for organization to which the contact belongs to. Can be found on the organization in BPS/GO.
      .PARAMETER Category
            Contacts category.
      .PARAMETER Position
            Contacts position.
      .PARAMETER ManagerID
            ID of contact that should be used as Manager.
      .PARAMETER Impact
            Contacts impact level. 1. Minor, 2. Medium or 3. Major.
      .PARAMETER PreferredMethodForNotification
            Contacts preferred method for notification. Mail or Telephone.
      .PARAMETER Building
            Buildning that the contact is located in.
      .PARAMETER Checkbox_Authorized_Purchaser
            Can be set to true or false.
      .PARAMETER Checkbox_Responsible_Manager
            Can be set to true or false.
      .PARAMETER Deparment
            Department to which the contact belongs.
      .PARAMETER Email
            Contacts email.
      .PARAMETER ExternalId
            Contacts external id.
      .PARAMETER FQDN
            Contacts fully qualified domain name.
      .PARAMETER Inactive
            Used to set contact as inactive. Can be set to true or false.
      .PARAMETER MobilePhone
            Contacts mobilephone.
      .PARAMETER Note
            Notes regarding contact.
      .PARAMETER Phone
            Contacts phone.
      .PARAMETER Room
            Room in which contact is located.
      .PARAMETER SecId
            Contacts security id.
      .PARAMETER Title
            Contact title, eg CEO.
      .PARAMETER Username
            Contacts username.
      .PARAMETER Attachment
            Full path to file to be included in payload.
      .PARAMETER SSO
            Used if system is using SSO with IWA (Active Directory). Not need when using SAML2
      .PARAMETER ShowDetails
            If specified, the response, including ID, will be displayed to host.
      .PARAMETER dryRun
            If specified, payload will be save as payload.xml to your desktop instead of sent to BPS.
      #>

      [CmdletBinding()]
      param (
            [parameter(Mandatory=$false,ValueFromPipelineByPropertyName=$true)]
            [ValidateNotNullOrEmpty()]
            [Alias("uri")]
            [string] $url = "http://localhost/webservice/",

            [parameter(Mandatory=$true,ValueFromPipelineByPropertyName=$true)]
            [ValidateNotNullOrEmpty()]
            [Alias("api")]
            [string] $apikey,

            [parameter(Mandatory=$false,ValueFromPipelineByPropertyName=$true)]
            [ValidateNotNullOrEmpty()]
            [Alias("ihi")]
            [string] $ImportHandlerIdentifier = "CreateContact",

            [parameter(ParameterSetName='BPSAttribute',ValueFromPipelineByPropertyName=$true)]
            [string] $FirstName,

            [parameter(ParameterSetName='BPSAttribute',ValueFromPipelineByPropertyName=$true)]
            [string] $Surname,

            [parameter(ParameterSetName='BPSAttribute',ValueFromPipelineByPropertyName=$true)]
            [string] $Email,

            [parameter(ParameterSetName='BPSAttribute',ValueFromPipelineByPropertyName=$true)]
            [int] $ID,

            [parameter(ParameterSetName='BPSAttribute',ValueFromPipelineByPropertyName=$true)]
            [string] $SecId,

            [parameter(ParameterSetName='BPSAttribute',ValueFromPipelineByPropertyName=$true)]
            [string] $OrganizationID,

            [parameter(ParameterSetName='BPSAttribute',ValueFromPipelineByPropertyName=$true)]
            [string] $Category,

            [parameter(ParameterSetName='BPSAttribute',ValueFromPipelineByPropertyName=$true)]
            [string] $Position,

            [parameter(ParameterSetName='BPSAttribute',ValueFromPipelineByPropertyName=$true)]
            [string] $ManagerID,

            [parameter(ParameterSetName='BPSAttribute',ValueFromPipelineByPropertyName=$true)]
            [string] $Impact,

            [parameter(ParameterSetName='BPSAttribute',ValueFromPipelineByPropertyName=$true)]
            [string] $PreferredMethodForNotification,

            [parameter(ParameterSetName='BPSAttribute',ValueFromPipelineByPropertyName=$true)]
            [string] $Building,

            [parameter(ParameterSetName='BPSAttribute',ValueFromPipelineByPropertyName=$true)]
            [string] $Checkbox_Authorized_Purchaser,

            [parameter(ParameterSetName='BPSAttribute',ValueFromPipelineByPropertyName=$true)]
            [string] $Checkbox_Responsible_Manager,

            [parameter(ParameterSetName='BPSAttribute',ValueFromPipelineByPropertyName=$true)]
            [string] $Deparment,

            [parameter(ParameterSetName='BPSAttribute',ValueFromPipelineByPropertyName=$true)]
            [string] $ExternalId,

            [parameter(ParameterSetName='BPSAttribute',ValueFromPipelineByPropertyName=$true)]
            [string] $FQDN,

            [parameter(ParameterSetName='BPSAttribute',ValueFromPipelineByPropertyName=$true)]
            [string] $Inactive,

            [parameter(ParameterSetName='BPSAttribute',ValueFromPipelineByPropertyName=$true)]
            [string] $MobilePhone,

            [parameter(ParameterSetName='BPSAttribute',ValueFromPipelineByPropertyName=$true)]
            [string] $Note,

            [parameter(ParameterSetName='BPSAttribute',ValueFromPipelineByPropertyName=$true)]
            [string] $Phone,

            [parameter(ParameterSetName='BPSAttribute',ValueFromPipelineByPropertyName=$true)]
            [string] $Room,

            [parameter(ParameterSetName='BPSAttribute',ValueFromPipelineByPropertyName=$true)]
            [string] $Title,

            [parameter(ParameterSetName='BPSAttribute',ValueFromPipelineByPropertyName=$true)]
            [string] $Username,

            [parameter(Mandatory=$false,ValueFromPipelineByPropertyName=$true)]
            [int] $uid = "1",

            [parameter(ParameterSetName='BPSAttribute',ValueFromPipelineByPropertyName=$true)]
            [Alias("File")]
            [string] $Attachment,

            [parameter(Mandatory=$false)]
            [switch] $SSO,

            [parameter(Mandatory=$false)]
            [switch] $dryRun,

            [parameter(Mandatory=$false)]
            [switch] $ShowDetails
      )

      try {
            Write-Verbose "Collecting list of used parameters"
            $CommandName = $PSCmdlet.MyInvocation.InvocationName
            $ParameterList = (Get-Command -Name $commandName).Parameters.Values
            Write-Verbose "Successfully collected list of used parameters"
      } catch {
            Write-Error 'Failed to get list of used parameters!'
            Write-Error "$_"
            break
      }

      Write-Verbose "Starting loop for creating hashtable of parameter..."
      $params = [ordered]@{}
      foreach ($parameter in $parameterList) {
            Write-Verbose "Starting loop for $($parameter.Name)"
            $ParameterSetToMatch = 'BPSAttribute'
            $parameterSets = $parameter.ParameterSets.Keys
            if ($parameterSets -contains $ParameterSetToMatch) {
                  Write-Verbose "$($parameter.Name) is part of BPS parameter set"
                  $parDetails = Get-Variable -Name $parameter.Name
                  if ($parDetails.Value) {
                        Write-Verbose "$($parameter.Name) have a value"
                        $parName = $parDetails.Name
                        $parValue = $parDetails.Value
                        $params.Add("$parName", "$parValue")
                  } else {
                        Write-Verbose "$($parameter.Name) does not have a value!"
                  }
            } else {
                  Write-Verbose "$($parameter.Name) is not part of BPS parameter set!"
            } Write-Verbose "Loop for $($parameter.Name) reached end!"
      }
      Write-Verbose "Successfully created hashtable of parameter!"
      $payload = New-XMLforEasit -Import -ImportHandlerIdentifier "$ImportHandlerIdentifier" -Params $Params

      if ($dryRun) {
            Write-Verbose "dryRun specified! Trying to save payload to file instead of sending it to BPS"
            $i = 1
            $currentUserProfile = [Environment]::GetEnvironmentVariable("USERPROFILE")
            $userProfileDesktop = "$currentUserProfile\Desktop"
            do {
                  $outputFileName = "payload_$i.xml"
                  if (Test-Path $userProfileDesktop\$outputFileName) {
                        $i++
                        Write-Host "$i"
                  }
            } until (!(Test-Path $userProfileDesktop\$outputFileName))
            if (!(Test-Path $userProfileDesktop\$outputFileName)) {
                  try {
                        $outputFileName = "payload_$i.xml"
                        $payload.Save("$userProfileDesktop\$outputFileName")
                        Write-Verbose "Saved payload to file, will now end!"
                        break
                  } catch {
                        Write-Error "Unable to save payload to file!"
                        Write-Error "$_"
                        break
                  }
            }
      }

      Write-Verbose "Creating header for web request!"
      try {
            $pair = "$($apikey): "
            $encodedCreds = [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes($pair))
            $basicAuthValue = "Basic $encodedCreds"
            $headers = @{SOAPAction = ""; Authorization = $basicAuthValue}
            Write-Verbose "Header created for web request!"
      } catch {
            Write-Error "Failed to create header!"
            Write-Error "$_"
            break
      }
      Write-Verbose "Calling web service and using payload as input for Body parameter"
      if ($SSO) {
            try {
                  Write-Verbose 'Using switch SSO. De facto UseDefaultCredentials for Invoke-WebRequest'
                  $r = Invoke-WebRequest -Uri $url -Method POST -ContentType 'text/xml' -Body $payload -Headers $headers -UseDefaultCredentials
                  Write-Verbose "Successfully connected to and imported data to BPS"
            } catch {
                  Write-Error "Failed to connect to BPS!"
                  Write-Error "$_"
                  return $payload
            }
      } else {
            try {
                  $r = Invoke-WebRequest -Uri $url -Method POST -ContentType 'text/xml' -Body $payload -Headers $headers
                  Write-Verbose "Successfully connected to and imported data to BPS"
            } catch {
                  Write-Error "Failed to connect to BPS!"
                  Write-Error "$_"
                  return $payload
            }
      }
      
      New-Variable -Name functionout
      [xml]$functionout = $r.Content
      Write-Verbose 'Casted content of reponse as [xml]$functionout'

      if ($ShowDetails) {
            $responseResult = $functionout.Envelope.Body.ImportItemsResponse.ImportItemResult.result
            $responseID = $functionout.Envelope.Body.ImportItemsResponse.ImportItemResult.ReturnValues.ReturnValue.InnerXml
            Write-Host "Result: $responseResult"
            Write-Host "ID for created item: $responseID"
      }
      Write-Verbose "Function complete!"
}

Export-ModuleMember -Function Import-GOContactItem
function Import-GOOrganizationItem {
      <#
      .SYNOPSIS
            Send data to BPS/GO with web services.
      .DESCRIPTION
            Update and create organization in Easit BPS/GO. Returns ID for item in Easit BPS/GO.
            Specify 'ID' to update an existing organization.

      .NOTES
            Copyright 2019 Easit AB

            Licensed under the Apache License, Version 2.0 (the "License");
            you may not use this file except in compliance with the License.
            You may obtain a copy of the License at

                http://www.apache.org/licenses/LICENSE-2.0

            Unless required by applicable law or agreed to in writing, software
            distributed under the License is distributed on an "AS IS" BASIS,
            WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
            See the License for the specific language governing permissions and
            limitations under the License.

      .LINK
            https://github.com/easitab/EasitGoWebservice/blob/master/EasitGoWebservice/Import-BPSContactItem.ps1

      .EXAMPLE
            Import-GOOrganizationItem -url http://localhost/webservice/ -apikey a8d5eba7f4daa79ea6f1c17c6b453d17df9c27727610b142c70c51bb4eda3618 -ImportHandlerIdentifier CreateOrganization_Internal -Name "IT and things" -ParentItemID "124" -CustomerNumber "1648752" -BusinessDebit "4687" -Country "Sverige" -Status "Active" -Verbose -ShowDetails
      .EXAMPLE
            Import-GOOrganizationItem -url http://localhost/webservice/ -apikey a8d5eba7f4daa79ea6f1c17c6b453d17df9c27727610b142c70c51bb4eda3618 -ihi CreateOrganization_External -Name "Stuff and IT" -CustomerNumber "4678524" -BusinessDebit "1684" -AccountManager "account.manager@company.com" -MainContractID "85" -ServiceManager "username123"
      .EXAMPLE
            Import-GOOrganizationItem -url http://localhost/webservice/ -api a8d5eba7f4daa79ea6f1c17c6b453d17df9c27727610b142c70c51bb4eda3618 -ImportHandlerIdentifier CreateOrganization_Supplier -ID "467" -Category "Food" -Status "Active"
      .EXAMPLE
            Import-GOOrganizationItem -url $url -apikey $api -ihi $identifier -ID "156" -Status "Inactive"
      .PARAMETER url
            Address to BPS/GO webservice. Default = http://localhost/webservice/
      .PARAMETER apikey
            API-key for BPS/GO.
      .PARAMETER ImportHandlerIdentifier
            ImportHandler to import data with. Default = CreateOrganization_Internal
      .PARAMETER Country
            Country that organization is located in or belongs to.
      .PARAMETER Category
            Category of organization.
      .PARAMETER Status
            Status of organization.
      .PARAMETER ParentItemID
            ID of parent organisation to organization.
      .PARAMETER MainContractID
            ID of main contract that organization is connected to.
      .PARAMETER ID
            ID of organization in BPS/GO.
      .PARAMETER AnvNamn
            Username at organization.
      .PARAMETER BusinessDebit
            BusinessDebit for organization.
      .PARAMETER Counterpart
            Counterpart for organization.
      .PARAMETER CustomerNumber
            Organization customer number
      .PARAMETER DeliveryAddress
            Delivery address for organization.
      .PARAMETER DeliveryCity
            Delivery city for organization (Leveransadress).
      .PARAMETER DeliveryZipCode
            Delivery zip code for organization.
      .PARAMETER ExternalId
            External id for organization. Can be used as unique identifier for integrations with other systems.
      .PARAMETER Fax
            Fax number for organization.
      .PARAMETER Losen
            Password at organization website.
      .PARAMETER Name
            Name of organization.
      .PARAMETER Notes
            Notes for organization.
      .PARAMETER Ort
            City for organization.
      .PARAMETER Phone
            Phone number for organization.
      .PARAMETER PostNummer
            Postal number for organization.
      .PARAMETER ResponsibilityDebit
            Responsibility debit for organization.
      .PARAMETER UtdelningsAdress
            Delivery address for organization (Utdelningsadress).
      .PARAMETER VisitingAddress
            Visiting address for organization.
      .PARAMETER VisitingCity
            Visiting city for organization.
      .PARAMETER VisitingZipCode
            Visiting zip code for organization.
      .PARAMETER Webshop
            URL to organizations webshop.
      .PARAMETER Website
            URL to organizations website.
      .PARAMETER AccountManager
            Email or username of user that should be used as AccountManager.
      .PARAMETER ServiceManager
            Email or username of user that should be used as ServiceManager.
      .PARAMETER Attachment
            Full path to file to be included in payload.
      .PARAMETER SSO
            Used if system is using SSO with IWA (Active Directory). Not need when using SAML2
      .PARAMETER ShowDetails
            If specified, the response, including ID, will be displayed to host.
      .PARAMETER dryRun
            If specified, payload will be save as payload.xml to your desktop instead of sent to BPS/GO.
      #>

      [CmdletBinding()]
      param (
            [parameter(Mandatory=$false,ValueFromPipelineByPropertyName=$true)]
            [ValidateNotNullOrEmpty()]
            [Alias("uri")]
            [string] $url = "http://localhost/webservice/",

            [parameter(Mandatory=$true,ValueFromPipelineByPropertyName=$true)]
            [ValidateNotNullOrEmpty()]
            [Alias("api")]
            [string] $apikey,

            [parameter(Mandatory=$false,ValueFromPipelineByPropertyName=$true)]
            [ValidateNotNullOrEmpty()]
            [Alias("ihi")]
            [string] $ImportHandlerIdentifier = "CreateOrganization_Internal",

            [parameter(ParameterSetName='BPSAttribute',ValueFromPipelineByPropertyName=$true)]
            [string] $Country,

            [parameter(ParameterSetName='BPSAttribute',ValueFromPipelineByPropertyName=$true)]
            [string] $Category,

            [parameter(ParameterSetName='BPSAttribute',ValueFromPipelineByPropertyName=$true)]
            [string] $Status,

            [parameter(ParameterSetName='BPSAttribute',ValueFromPipelineByPropertyName=$true)]
            [Alias("Parent")]
            [int] $ParentItemID,

            [parameter(ParameterSetName='BPSAttribute',ValueFromPipelineByPropertyName=$true)]
            [Alias("Contract")]
            [string] $MainContractID,

            [parameter(ParameterSetName='BPSAttribute',ValueFromPipelineByPropertyName=$true)]
            [Alias("OrganizationID")]
            [string] $ID,

            [parameter(ParameterSetName='BPSAttribute',ValueFromPipelineByPropertyName=$true)]
            [Alias("UserName")]
            [string] $AnvNamn,

            [parameter(ParameterSetName='BPSAttribute',ValueFromPipelineByPropertyName=$true)]
            [Alias("Verksamhetdebet")]
            [string] $BusinessDebit,

            [parameter(ParameterSetName='BPSAttribute',ValueFromPipelineByPropertyName=$true)]
            [string] $Counterpart,

            [parameter(ParameterSetName='BPSAttribute',ValueFromPipelineByPropertyName=$true)]
            [string] $CustomerNumber,

            [parameter(ParameterSetName='BPSAttribute',ValueFromPipelineByPropertyName=$true)]
            [string] $DeliveryAddress,

            [parameter(ParameterSetName='BPSAttribute',ValueFromPipelineByPropertyName=$true)]
            [string] $DeliveryCity,

            [parameter(ParameterSetName='BPSAttribute',ValueFromPipelineByPropertyName=$true)]
            [string] $DeliveryZipCode,

            [parameter(ParameterSetName='BPSAttribute',ValueFromPipelineByPropertyName=$true)]
            [string] $ExternalId,

            [parameter(ParameterSetName='BPSAttribute',ValueFromPipelineByPropertyName=$true)]
            [string] $Fax,

            [parameter(ParameterSetName='BPSAttribute',ValueFromPipelineByPropertyName=$true)]
            [Alias("Password")]
            [string] $Losen,

            [parameter(ParameterSetName='BPSAttribute',ValueFromPipelineByPropertyName=$true)]
            [Alias("Namn")]
            [string] $Name,

            [parameter(ParameterSetName='BPSAttribute',ValueFromPipelineByPropertyName=$true)]
            [Alias("Anteckningar")]
            [string] $Notes,

            [parameter(ParameterSetName='BPSAttribute',ValueFromPipelineByPropertyName=$true)]
            [Alias("City")]
            [string] $Ort,

            [parameter(ParameterSetName='BPSAttribute',ValueFromPipelineByPropertyName=$true)]
            [Alias("Telefon")]
            [string] $Phone,

            [parameter(ParameterSetName='BPSAttribute',ValueFromPipelineByPropertyName=$true)]
            [string] $PostNummer,

            [parameter(ParameterSetName='BPSAttribute',ValueFromPipelineByPropertyName=$true)]
            [Alias("Ansvardebet")]
            [string] $ResponsibilityDebit,

            [parameter(ParameterSetName='BPSAttribute',ValueFromPipelineByPropertyName=$true)]
            [string] $UtdelningsAdress,

            [parameter(ParameterSetName='BPSAttribute',ValueFromPipelineByPropertyName=$true)]
            [Alias("Besoksadress")]
            [string] $VisitingAddress,

            [parameter(ParameterSetName='BPSAttribute',ValueFromPipelineByPropertyName=$true)]
            [Alias("Besoksort")]
            [string] $VisitingCity,

            [parameter(ParameterSetName='BPSAttribute',ValueFromPipelineByPropertyName=$true)]
            [Alias("Besokspostnummer")]
            [string] $VisitingZipCode,

            [parameter(ParameterSetName='BPSAttribute',ValueFromPipelineByPropertyName=$true)]
            [string] $Webshop,

            [parameter(ParameterSetName='BPSAttribute',ValueFromPipelineByPropertyName=$true)]
            [Alias("Webb","homepage")]
            [string] $Website,

            [parameter(ParameterSetName='BPSAttribute',ValueFromPipelineByPropertyName=$true)]
            [Alias("Kundansvarig")]
            [string] $AccountManager,

            [parameter(ParameterSetName='BPSAttribute',ValueFromPipelineByPropertyName=$true)]
            [Alias("Serviceansvarig")]
            [string] $ServiceManager,

            [parameter(Mandatory=$false,ValueFromPipelineByPropertyName=$true)]
            [int] $uid = "1",

            [parameter(ParameterSetName='BPSAttribute',ValueFromPipelineByPropertyName=$true)]
            [Alias("File")]
            [string] $Attachment,

            [parameter(Mandatory=$false)]
            [switch] $SSO,

            [parameter(Mandatory=$false)]
            [switch] $dryRun,

            [parameter(Mandatory=$false)]
            [switch] $ShowDetails
      )

      try {
            Write-Verbose "Collecting list of used parameters"
            $CommandName = $PSCmdlet.MyInvocation.InvocationName
            $ParameterList = (Get-Command -Name $commandName).Parameters.Values
            Write-Verbose "Successfully collected list of used parameters"
      } catch {
            Write-Error 'Failed to get list of used parameters!'
            Write-Error "$_"
            break
      }

      Write-Verbose "Starting loop for creating hashtable of parameter..."
      $params = [ordered]@{}
      foreach ($parameter in $parameterList) {
            Write-Verbose "Starting loop for $($parameter.Name)"
            $ParameterSetToMatch = 'BPSAttribute'
            $parameterSets = $parameter.ParameterSets.Keys
            if ($parameterSets -contains $ParameterSetToMatch) {
                  Write-Verbose "$($parameter.Name) is part of BPS parameter set"
                  $parDetails = Get-Variable -Name $parameter.Name
                  if ($parDetails.Value) {
                        Write-Verbose "$($parameter.Name) have a value"
                        $parName = $parDetails.Name
                        $parValue = $parDetails.Value
                        $params.Add("$parName", "$parValue")
                  } else {
                        Write-Verbose "$($parameter.Name) does not have a value!"
                  }
            } else {
                  Write-Verbose "$($parameter.Name) is not part of BPS parameter set!"
            } Write-Verbose "Loop for $($parameter.Name) reached end!"
      }
      Write-Verbose "Successfully created hashtable of parameter!"
      $payload = New-XMLforEasit -Import -ImportHandlerIdentifier "$ImportHandlerIdentifier" -Params $Params

      if ($dryRun) {
            Write-Verbose "dryRun specified! Trying to save payload to file instead of sending it to BPS"
            $i = 1
            $currentUserProfile = [Environment]::GetEnvironmentVariable("USERPROFILE")
            $userProfileDesktop = "$currentUserProfile\Desktop"
            do {
                  $outputFileName = "payload_$i.xml"
                  if (Test-Path $userProfileDesktop\$outputFileName) {
                        $i++
                        Write-Host "$i"
                  }
            } until (!(Test-Path $userProfileDesktop\$outputFileName))
            if (!(Test-Path $userProfileDesktop\$outputFileName)) {
                  try {
                        $outputFileName = "payload_$i.xml"
                        $payload.Save("$userProfileDesktop\$outputFileName")
                        Write-Verbose "Saved payload to file, will now end!"
                        break
                  } catch {
                        Write-Error "Unable to save payload to file!"
                        Write-Error "$_"
                        break
                  }
            }
      }

      Write-Verbose "Creating header for web request!"
      try {
            $pair = "$($apikey): "
            $encodedCreds = [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes($pair))
            $basicAuthValue = "Basic $encodedCreds"
            $headers = @{SOAPAction = ""; Authorization = $basicAuthValue}
            Write-Verbose "Header created for web request!"
      } catch {
            Write-Error "Failed to create header!"
            Write-Error "$_"
            break
      }
      Write-Verbose "Calling web service and using payload as input for Body parameter"
      if ($SSO) {
            try {
                  Write-Verbose 'Using switch SSO. De facto UseDefaultCredentials for Invoke-WebRequest'
                  $r = Invoke-WebRequest -Uri $url -Method POST -ContentType 'text/xml' -Body $payload -Headers $headers -UseDefaultCredentials
                  Write-Verbose "Successfully connected to and imported data to BPS"
            } catch {
                  Write-Error "Failed to connect to BPS!"
                  Write-Error "$_"
                  return $payload
            }
      } else {
            try {
                  $r = Invoke-WebRequest -Uri $url -Method POST -ContentType 'text/xml' -Body $payload -Headers $headers
                  Write-Verbose "Successfully connected to and imported data to BPS"
            } catch {
                  Write-Error "Failed to connect to BPS!"
                  Write-Error "$_"
                  return $payload
            }
      }
      
      New-Variable -Name functionout
      [xml]$functionout = $r.Content
      Write-Verbose 'Casted content of reponse as [xml]$functionout'

      if ($ShowDetails) {
            $responseResult = $functionout.Envelope.Body.ImportItemsResponse.ImportItemResult.result
            $responseID = $functionout.Envelope.Body.ImportItemsResponse.ImportItemResult.ReturnValues.ReturnValue.InnerXml
            Write-Host "Result: $responseResult"
            Write-Host "ID for created item: $responseID"
      }
      Write-Verbose "Function complete!"
}
Export-ModuleMember -Function Import-GOOrganizationItem
function Import-GORequestItem {
      <#
      .SYNOPSIS
            Send data to BPS/GO with web services.
      .DESCRIPTION
            Update and create requests in Easit BPS/GO. Returns ID for item in Easit BPS/GO..
            Specify 'ID' to update an existing item.

      .NOTES
            Copyright 2019 Easit AB

            Licensed under the Apache License, Version 2.0 (the "License");
            you may not use this file except in compliance with the License.
            You may obtain a copy of the License at

                http://www.apache.org/licenses/LICENSE-2.0

            Unless required by applicable law or agreed to in writing, software
            distributed under the License is distributed on an "AS IS" BASIS,
            WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
            See the License for the specific language governing permissions and
            limitations under the License.

      .LINK
            https://github.com/easitab/EasitGoWebservice/blob/master/EasitGoWebservice/Import-GORequestItem.ps1

      .EXAMPLE
            Import-GORequestItem -url http://localhost/webservice/ -apikey a8d5eba7f4daa79ea6f1c17c6b453d17df9c27727610b142c70c51bb4eda3618 -ImportHandlerIdentifier CreateRequest -Subject Testing1 -Description Testing1 -ContactID 5 -Status Registrerad -Verbose -ShowDetails
      .EXAMPLE
            Import-GORequestItem -url http://localhost/webservice/ -apikey a8d5eba7f4daa79ea6f1c17c6b453d17df9c27727610b142c70c51bb4eda3618 -ImportHandlerIdentifier CreateRequest -Subject Testing1 -Description Testing1 -ContactID 5 -Status Registrerad
      .EXAMPLE
            Import-GORequestItem -url http://localhost/webservice/ -apikey a8d5eba7f4daa79ea6f1c17c6b453d17df9c27727610b142c70c51bb4eda3618 -ImportHandlerIdentifier CreateRequest -ID "156" -Description "Testing2. Nytt test!"
      .EXAMPLE
            Import-GORequestItem -url $url -apikey $api -ihi $identifier -ID "156" -Description "Updating description for request 156"
      .PARAMETER url
            Address to BPS/GO webservice. Default = http://localhost/webservice/
      .PARAMETER apikey
            API-key for BPS/GO.
      .PARAMETER ImportHandlerIdentifier
            ImportHandler to import data with. Default = CreateRequest
      .PARAMETER ID
            ID for request in BPS/GO. Existing item will be updated if provided.
      .PARAMETER ContactID
            ID of contact in BPS/GO. Can be found on the contact in BPS/GO.
      .PARAMETER OrganizationID
            ID for organization to which the contact belongs to. Can be found on the organization in BPS/GO.
      .PARAMETER Category
            Contacts category.
      .PARAMETER ManagerGroup
            Name of manager group
      .PARAMETER Manager
            Username or email of user that should be used as manager.
      .PARAMETER Type
            Name of type. Matches agains existing types.
      .PARAMETER Status
            Name of status. Matches agains existing statuses.
      .PARAMETER ParentItemID
            ID of parent item. Matches agains existing items.
      .PARAMETER Priority
            Priority for item. Matches agains existing priorities.
      .PARAMETER Description
            Description of request.
      .PARAMETER FaqKnowledgeResolutionText
            Solution for the request.
      .PARAMETER Subject
            Subject of request.
      .PARAMETER AssetsCollectionID
            ID of asset to connect to the request. Adds item to collection.
      .PARAMETER CausalField
            Closure cause.
      .PARAMETER ClosingCategory
            Closure category.
      .PARAMETER Impact
            Impact of request.
      .PARAMETER Owner
            Owner of request.
      .PARAMETER ReferenceContactID
            ID of reference contact. Can be found on the contact in BPS/GO.
      .PARAMETER ReferenceOrganizationID
            ID of reference organization. Can be found on the organization in BPS/GO.
      .PARAMETER ServiceID
            ID of article to connect with request. Can be found on the article in BPS/GO.
      .PARAMETER SLAID
            ID of contract to connect with request. Can be found on the contract in BPS/GO.
      .PARAMETER Urgency
            Urgency of request.
      .PARAMETER ClassificationID
            ID of classification to connect with request. Can be found on the classification in BPS/GO.
      .PARAMETER KnowledgebaseArticleID
            ID of knowledgebase article to connect with request. Can be found on the knowledgebase article in BPS/GO.
      .PARAMETER Attachment
            Full path to file to be included in payload.
      .PARAMETER SSO
            Used if system is using SSO with IWA (Active Directory). Not need when using SAML2
      .PARAMETER ShowDetails
            If specified, the response, including ID, will be displayed to host.
      .PARAMETER dryRun
            If specified, payload will be save as payload.xml to your desktop instead of sent to BPS/GO.
      #>

      [CmdletBinding()]
      param (
            [parameter(Mandatory=$false,ValueFromPipelineByPropertyName=$true)]
            [ValidateNotNullOrEmpty()]
            [Alias("uri")]
            [string] $url = "http://localhost/webservice/",

            [parameter(Mandatory=$true,ValueFromPipelineByPropertyName=$true)]
            [ValidateNotNullOrEmpty()]
            [Alias("api")]
            [string] $apikey,

            [parameter(Mandatory=$false,ValueFromPipelineByPropertyName=$true)]
            [ValidateNotNullOrEmpty()]
            [Alias('ihi')]
            [string] $ImportHandlerIdentifier = 'CreateRequest',

            [parameter(ParameterSetName='BPSAttribute',ValueFromPipelineByPropertyName=$true)]
            [Alias('Item','ItemID')]
            [int] $ID,

            [parameter(ParameterSetName='BPSAttribute',ValueFromPipelineByPropertyName=$true)]
            [int] $ContactID,

            [parameter(ParameterSetName='BPSAttribute',ValueFromPipelineByPropertyName=$true)]
            [int] $OrganizationID,

            [parameter(ParameterSetName='BPSAttribute',ValueFromPipelineByPropertyName=$true)]
            [string] $Category,

            [parameter(ParameterSetName='BPSAttribute',ValueFromPipelineByPropertyName=$true)]
            [string] $ManagerGroup,

            [parameter(ParameterSetName='BPSAttribute',ValueFromPipelineByPropertyName=$true)]
            [string] $Manager,

            [parameter(ParameterSetName='BPSAttribute',ValueFromPipelineByPropertyName=$true)]
            [string] $Type,

            [parameter(ParameterSetName='BPSAttribute',ValueFromPipelineByPropertyName=$true)]
            [string] $Status,

            [parameter(ParameterSetName='BPSAttribute',ValueFromPipelineByPropertyName=$true)]
            [Alias('Parent')]
            [int] $ParentItemID,

            [parameter(ParameterSetName='BPSAttribute',ValueFromPipelineByPropertyName=$true)]
            [string] $Priority,

            [parameter(ParameterSetName='BPSAttribute',ValueFromPipelineByPropertyName=$true)]
            [string] $Description,

            [parameter(ParameterSetName='BPSAttribute',ValueFromPipelineByPropertyName=$true)]
            [Alias('Resolution','FAQ')]
            [string] $FaqKnowledgeResolutionText,

            [parameter(ParameterSetName='BPSAttribute',ValueFromPipelineByPropertyName=$true)]
            [string] $Subject,

            [parameter(ParameterSetName='BPSAttribute',ValueFromPipelineByPropertyName=$true)]
            [Alias('Asset')]
            [int] $AssetsCollectionID,

            [parameter(ParameterSetName='BPSAttribute',ValueFromPipelineByPropertyName=$true)]
            [Alias('ClosureCause')]
            [string] $CausalField,

            [parameter(ParameterSetName='BPSAttribute',ValueFromPipelineByPropertyName=$true)]
            [string] $ClosingCategory,

            [parameter(ParameterSetName='BPSAttribute',ValueFromPipelineByPropertyName=$true)]
            [string] $Impact,

            [parameter(ParameterSetName='BPSAttribute',ValueFromPipelineByPropertyName=$true)]
            [string] $Owner,

            [parameter(ParameterSetName='BPSAttribute',ValueFromPipelineByPropertyName=$true)]
            [int] $ReferenceContactID,

            [parameter(ParameterSetName='BPSAttribute',ValueFromPipelineByPropertyName=$true)]
            [int] $ReferenceOrganizationID,

            [parameter(ParameterSetName='BPSAttribute',ValueFromPipelineByPropertyName=$true)]
            [Alias('Article')]
            [int] $ServiceID,

            [parameter(ParameterSetName='BPSAttribute',ValueFromPipelineByPropertyName=$true)]
            [Alias('SLA')]
            [string] $SLAID,

            [parameter(ParameterSetName='BPSAttribute',ValueFromPipelineByPropertyName=$true)]
            [string] $Urgency,

            [parameter(ParameterSetName='BPSAttribute',ValueFromPipelineByPropertyName=$true)]
            [Alias('Classification')]
            [int] $ClassificationID,

            [parameter(ParameterSetName='BPSAttribute',ValueFromPipelineByPropertyName=$true)]
            [Alias('KnowledgebaseArticle','KB')]
            [int] $KnowledgebaseArticleID,

            [parameter(ParameterSetName='BPSAttribute',ValueFromPipelineByPropertyName=$true)]
            [Alias('CI')]
            [int] $CIID,

            [parameter(Mandatory=$false,ValueFromPipelineByPropertyName=$true)]
            [int] $uid = "1",

            [parameter(ParameterSetName='BPSAttribute',ValueFromPipelineByPropertyName=$true)]
            [Alias("File")]
            [string] $Attachment,

            [parameter(Mandatory=$false)]
            [switch] $SSO,

            [parameter(Mandatory=$false)]
            [switch] $dryRun,

            [parameter(Mandatory=$false)]
            [switch] $ShowDetails
      )

      try {
            Write-Verbose "Collecting list of used parameters"
            $CommandName = $PSCmdlet.MyInvocation.InvocationName
            $ParameterList = (Get-Command -Name $commandName).Parameters.Values
            Write-Verbose "Successfully collected list of used parameters"
      } catch {
            Write-Error 'Failed to get list of used parameters!'
            Write-Error "$_"
            break
      }

      Write-Verbose "Starting loop for creating hashtable of parameter..."
      $params = [ordered]@{}
      foreach ($parameter in $parameterList) {
            Write-Verbose "Starting loop for $($parameter.Name)"
            $ParameterSetToMatch = 'BPSAttribute'
            $parameterSets = $parameter.ParameterSets.Keys
            if ($parameterSets -contains $ParameterSetToMatch) {
                  Write-Verbose "$($parameter.Name) is part of BPS parameter set"
                  $parDetails = Get-Variable -Name $parameter.Name
                  if ($parDetails.Value) {
                        Write-Verbose "$($parameter.Name) have a value"
                        $parName = $parDetails.Name
                        $parValue = $parDetails.Value
                        $params.Add("$parName", "$parValue")
                  } else {
                        Write-Verbose "$($parameter.Name) does not have a value!"
                  }
            } else {
                  Write-Verbose "$($parameter.Name) is not part of BPS parameter set!"
            } Write-Verbose "Loop for $($parameter.Name) reached end!"
      }
      Write-Verbose "Successfully created hashtable of parameter!"
      $payload = New-XMLforEasit -Import -ImportHandlerIdentifier "$ImportHandlerIdentifier" -Params $Params

      if ($dryRun) {
            Write-Verbose "dryRun specified! Trying to save payload to file instead of sending it to BPS"
            $i = 1
            $currentUserProfile = [Environment]::GetEnvironmentVariable("USERPROFILE")
            $userProfileDesktop = "$currentUserProfile\Desktop"
            do {
                  $outputFileName = "payload_$i.xml"
                  if (Test-Path $userProfileDesktop\$outputFileName) {
                        $i++
                        Write-Host "$i"
                  }
            } until (!(Test-Path $userProfileDesktop\$outputFileName))
            if (!(Test-Path $userProfileDesktop\$outputFileName)) {
                  try {
                        $outputFileName = "payload_$i.xml"
                        $payload.Save("$userProfileDesktop\$outputFileName")
                        Write-Verbose "Saved payload to file, will now end!"
                        break
                  } catch {
                        Write-Error "Unable to save payload to file!"
                        Write-Error "$_"
                        break
                  }
            }
      }

      Write-Verbose "Creating header for web request!"
      try {
            $pair = "$($apikey): "
            $encodedCreds = [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes($pair))
            $basicAuthValue = "Basic $encodedCreds"
            $headers = @{SOAPAction = ""; Authorization = $basicAuthValue}
            Write-Verbose "Header created for web request!"
      } catch {
            Write-Error "Failed to create header!"
            Write-Error "$_"
            break
      }
      Write-Verbose "Calling web service and using payload as input for Body parameter"
      if ($SSO) {
            try {
                  Write-Verbose 'Using switch SSO. De facto UseDefaultCredentials for Invoke-WebRequest'
                  $r = Invoke-WebRequest -Uri $url -Method POST -ContentType 'text/xml' -Body $payload -Headers $headers -UseDefaultCredentials
                  Write-Verbose "Successfully connected to and imported data to BPS"
            } catch {
                  Write-Error "Failed to connect to BPS!"
                  Write-Error "$_"
                  return $payload
            }
      } else {
            try {
                  $r = Invoke-WebRequest -Uri $url -Method POST -ContentType 'text/xml' -Body $payload -Headers $headers
                  Write-Verbose "Successfully connected to and imported data to BPS"
            } catch {
                  Write-Error "Failed to connect to BPS!"
                  Write-Error "$_"
                  return $payload
            }
      }
      
      New-Variable -Name functionout
      [xml]$functionout = $r.Content
      Write-Verbose 'Casted content of reponse as [xml]$functionout'

      if ($ShowDetails) {
            $responseResult = $functionout.Envelope.Body.ImportItemsResponse.ImportItemResult.result
            $responseID = $functionout.Envelope.Body.ImportItemsResponse.ImportItemResult.ReturnValues.ReturnValue.InnerXml
            Write-Host "Result: $responseResult"
            Write-Host "ID for created item: $responseID"
      }
      Write-Verbose "Function complete!"
}
Export-ModuleMember -Function Import-GORequestItem
function New-XMLforEasit {
    [CmdletBinding()]
    param (
        [parameter(Mandatory=$false, Position=0, ParameterSetName="ping")]
        [switch] $Ping,

        [parameter(Mandatory=$false, Position=0, ParameterSetName="get")]
        [switch] $Get,

        [Parameter(Mandatory=$true, ParameterSetName="get")]
        [string] $ItemViewIdentifier,

        [Parameter(Mandatory=$false, ParameterSetName="get")]
        [int] $Page = 1,

        [Parameter(Mandatory=$true, ParameterSetName="get")]
        [string] $SortField,
        
        [Parameter(Mandatory=$true, ParameterSetName="get")]
        [string] $SortOrder,

        [Parameter(Mandatory=$false, ParameterSetName="get")]
        [string[]] $ColumnFilter,

        [parameter(Mandatory=$false, Position=0, ParameterSetName="import")]
        [switch] $Import,

        [Parameter(Mandatory=$true, ParameterSetName="import")]
        [string] $ImportHandlerIdentifier,

        [Parameter(Mandatory=$true, ParameterSetName="import")]
        [hashtable] $Params
    )



    Write-Verbose "Defining xmlns:soapenv and xmlns:sch"
    $xmlnsSoapEnv = "http://schemas.xmlsoap.org/soap/envelope/"
    $xmlnsSch = "http://www.easit.com/bps/schemas"

    try {
        Write-Verbose "Creating xml object for payload"
        $payload = New-Object xml
        [System.Xml.XmlDeclaration] $xmlDeclaration = $payload.CreateXmlDeclaration("1.0", "UTF-8", $null)
        $payload.AppendChild($xmlDeclaration) | Out-Null
    } catch {
        Write-Error "Failed to create xml object for payload"
        Write-Error "$_"
        break
    }

    try {
        Write-Verbose "Creating xml element for Envelope"
        $soapEnvEnvelope = $payload.CreateElement("soapenv:Envelope","$xmlnsSoapEnv")
        $soapEnvEnvelope.SetAttribute("xmlns:sch","$xmlnsSch")
        $payload.AppendChild($soapEnvEnvelope) | Out-Null
    } catch {
        Write-Error "Failed to create xml element for Envelope"
        Write-Error "$_"
        break
    }

    try {
        Write-Verbose "Creating xml element for Header"
        $soapEnvHeader = $payload.CreateElement('soapenv:Header',"$xmlnsSoapEnv")
        $soapEnvEnvelope.AppendChild($soapEnvHeader) | Out-Null
    } catch {
        Write-Error "Failed to create xml element for Header"
        Write-Error "$_"
        break
    }

    try {
        Write-Verbose "Creating xml element for Body"
        $soapEnvBody = $payload.CreateElement("soapenv:Body","$xmlnsSoapEnv")
        $soapEnvEnvelope.AppendChild($soapEnvBody) | Out-Null
    } catch {
        Write-Error "Failed to create xml element for Body"
        Write-Error "$_"
        break
    }


    if ($Import) {
        try {
            Write-Verbose "Creating xml element for ImportItemsRequest"
            $schImportItemsRequest = $payload.CreateElement("sch:ImportItemsRequest","$xmlnsSch")
            $soapEnvBody.AppendChild($schImportItemsRequest) | Out-Null
        } catch {
            Write-Error "Failed to create xml element for ImportItemsRequest"
            Write-Error "$_"
            break
        }
        try {
            Write-Verbose "Creating xml element for Importhandler"
            $envelopeImportHandlerIdentifier = $payload.CreateElement('sch:ImportHandlerIdentifier',"$xmlnsSch")
            $envelopeImportHandlerIdentifier.InnerText  = "$ImportHandlerIdentifier"
            $schImportItemsRequest.AppendChild($envelopeImportHandlerIdentifier) | Out-Null
        } catch {
            Write-Error "Failed to create xml element for Importhandler"
            Write-Error "$_"
            break
        }
    
        try {
            Write-Verbose "Creating xml element for ItemToImport"
            $schItemToImport = $payload.CreateElement("sch:ItemToImport","$xmlnsSch")
            $schItemToImport.SetAttribute("id","$uid")
            $schItemToImport.SetAttribute("uid","$uid")
            $schImportItemsRequest.AppendChild($schItemToImport) | Out-Null
        } catch {
            Write-Error "Failed to create xml element for ItemToImport"
            Write-Error "$_"
            break
        }
        Write-Verbose "Starting loop for creating xml element for each parameter"
        foreach ($parameter in $Params.GetEnumerator()) {
            Write-Verbose "Starting loop for $($parameter.Name) with value $($parameter.Value)"
            if ($parameter.Name -eq "Attachment") {
                try {
                    $parName = $parameter.Name
                    $parValue = $parameter.Value
                    $fileHeader = ""
                    $separator = "\"
                    $fileNametoHeader = $parValue.Split($separator)
                    $fileHeader = $fileNametoHeader[-1]
                    $base64string = [Convert]::ToBase64String([System.IO.File]::ReadAllBytes("$parValue"))
                    $envelopeItemAttachment = $payload.CreateElement("sch:Attachment","$xmlnsSch")
                    $envelopeItemAttachment.SetAttribute('name',"$fileHeader")
                    $envelopeItemAttachment.InnerText = $base64string
                    $schItemToImport.AppendChild($envelopeItemAttachment) | Out-Null
                    Write-Verbose "Added property $parName to payload!"
                } catch {
                    Write-Error "Failed to add property $parName in SOAP envelope!"
                    Write-Error "$_"
                }
            } else {
                $parName = $parameter.Name
                $parValue = $parameter.Value
                try {
                    $envelopeItemProperty = $payload.CreateElement("sch:Property","$xmlnsSch")
                    $envelopeItemProperty.SetAttribute('name',"$parName")
                    $envelopeItemProperty.InnerText = $parValue
                    $schItemToImport.AppendChild($envelopeItemProperty) | Out-Null
                    Write-Verbose "Added property $parName to payload!"
                } catch {
                    Write-Error "Failed to add property $parName in SOAP envelope!"
                    Write-Error "$_"
                }
            }
        } Write-Verbose "Loop for $($parameter.Name) reached end!"
    }

    if ($Get) {
        try {
            Write-Verbose "Creating xml element for GetItemsRequest"
            $schGetItemsRequest = $payload.CreateElement("sch:GetItemsRequest","$xmlnsSch")
            $soapEnvBody.AppendChild($schGetItemsRequest) | Out-Null
        } catch {
            Write-Error "Failed to create xml element for GetItemsRequest"
            Write-Error "$_"
            break
        }

        try {
            Write-Verbose "Creating xml element for ItemViewIdentifier"
            $envelopeItemViewIdentifier = $payload.CreateElement('sch:ItemViewIdentifier',"$xmlnsSch")
            $envelopeItemViewIdentifier.InnerText  = "$ItemViewIdentifier"
            $schGetItemsRequest.AppendChild($envelopeItemViewIdentifier) | Out-Null
        } catch {
            Write-Error "Failed to create xml element for ItemViewIdentifier"
            Write-Error "$_"
            break
        }

        try {
            Write-Verbose "Creating xml element for Page"
            $envelopePage = $payload.CreateElement('sch:Page',"$xmlnsSch")
            $envelopePage.InnerText  = "$Page"
            $schGetItemsRequest.AppendChild($envelopePage) | Out-Null
        } catch {
            Write-Error "Failed to create xml element for Page"
            Write-Error "$_"
            break
        }

        try {
            Write-Verbose "Creating xml element for SortColumn order"
            $envelopeSortColumnOrder = $payload.CreateElement('sch:SortColumn',"$xmlnsSch")
            $envelopeSortColumnOrder.SetAttribute("order","$SortOrder")
            $envelopeSortColumnOrder.InnerText  = "$SortField"
            $schGetItemsRequest.AppendChild($envelopeSortColumnOrder) | Out-Null
        } catch {
            Write-Error "Failed to create xml element for Page"
            Write-Error "$_"
            break
        }
        if ($ColumnFilter) {
            try {
                $ColumnFilterValues = $ColumnFilter -split ','
                [int]$ColumnFilterValuesCount = $ColumnFilterValues.Count
                #$i=0 | Out-Null
                #do {
                    Write-Verbose "Creating xml element for Column filter"
                    $envelopeColumnFilter1 = $payload.CreateElement('sch:ColumnFilter',"$xmlnsSch")
                    $envelopeColumnFilter1.SetAttribute("columnName","$($ColumnFilterValues[0])")
                    $envelopeColumnFilter1.SetAttribute("comparator","$($ColumnFilterValues[1])")
                    $envelopeColumnFilter1.InnerText  = "$($ColumnFilterValues[2])"
                    $schGetItemsRequest.AppendChild($envelopeColumnFilter1) | Out-Null
                    if ($ColumnFilterValuesCount -gt 2) {
                        $envelopeColumnFilter2 = $payload.CreateElement('sch:ColumnFilter',"$xmlnsSch")
                        $envelopeColumnFilter2.SetAttribute("columnName","$($ColumnFilterValues[3])")
                        $envelopeColumnFilter2.SetAttribute("comparator","$($ColumnFilterValues[4])")
                        $envelopeColumnFilter2.InnerText  = "$($ColumnFilterValues[5])"
                        $schGetItemsRequest.AppendChild($envelopeColumnFilter2) | Out-Null
                    }
                    #$i+3 | Out-Null
                #} until ($i -le $ColumnFilterValuesCount)
            } catch {
                Write-Error "Failed to create xml element for ColumnFilter"
                Write-Error "$_"
                break
            }
        } else {
            Write-Verbose "Skipping ColumnFilter as it is null!"
        }
    }

    if ($Ping) {
        try {
            Write-Verbose "Creating xml element for PingRequest"
            $envelopePingRequest = $payload.CreateElement('sch:PingRequest',"$xmlnsSch")
            $envelopePingRequest.InnerText  = '?'
            $soapEnvBody.AppendChild($envelopePingRequest) | Out-Null
      } catch {
            Write-Error "Failed to create xml element for PingRequest"
            Write-Error "$_"
            break
      }
    }
    if ($PSCmdlet.MyInvocation.BoundParameters["Verbose"].IsPresent) {
        $payload.Save("$HOME\Documents\payload.xml")
    }
    Write-Verbose "Successfully updated property values in SOAP envelope for all parameters with input provided!"
    return $payload
}
Export-ModuleMember -Function New-XMLforEasit
function Ping-GOWebService {
      <#
      .SYNOPSIS
            Ping BPS/GO web services.
      .DESCRIPTION
            Can be used to check if service is available and correct credentials have been provided..

      .NOTES
            Copyright 2019 Easit AB

            Licensed under the Apache License, Version 2.0 (the "License");
            you may not use this file except in compliance with the License.
            You may obtain a copy of the License at

                http://www.apache.org/licenses/LICENSE-2.0

            Unless required by applicable law or agreed to in writing, software
            distributed under the License is distributed on an "AS IS" BASIS,
            WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
            See the License for the specific language governing permissions and
            limitations under the License.

      .LINK
            https://github.com/easitab/EasitGoWebservice/blob/master/EasitGoWebservice/Ping-GOWebService.ps1

      .EXAMPLE
            Ping-GOWebService -url http://localhost/test/webservice/ -apikey 4745f62b7371c2aa5cb80be8cd56e6372f495f6g8c60494ek7f231548bb2a375
      .PARAMETER url
            Address to BPS/GO webservice. Default = http://localhost/webservice/
      .PARAMETER apikey
            API key for BPS/GO.
      #>

      [CmdletBinding()]
      param (
            [parameter(Mandatory=$false)]
            [string] $url = "http://localhost/webservice/",

            [parameter(Mandatory=$true)]
            [Alias("api")]
            [string] $apikey
      )

      $payload = New-XMLforEasit -Ping

      Write-Verbose "Creating header for web request!"
      try {
            $pair = "$($apikey): "
            $encodedCreds = [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes($pair))
            $basicAuthValue = "Basic $encodedCreds"
            $headers = @{SOAPAction = ""; Authorization = $basicAuthValue}
            Write-Verbose "Header created for web request!"
      } catch {
            Write-Error "Failed to create header!"
            Write-Error "$_"
            break
      }
      Write-Verbose "Calling web service"
      try {
            $r = Invoke-WebRequest -Uri $url -Method POST -ContentType 'text/xml' -Body $payload -Headers $headers
            Write-Verbose "Successfully connected to web service"
      } catch {
            Write-Error "Failed to connect to BPS!"
            Write-Error "$_"
            return $payload
      }
      Write-Verbose 'Successfully connected to and recieved data from web service'
      [xml]$functionout = $r.Content
      Write-Verbose 'Casted content of reponse as [xml]$functionout'
      Write-Verbose 'Returning $functionout.Envelope.Body.PingResponse.Message (Pong!)'
      return $functionout.Envelope.Body.PingResponse.Message
}
Export-ModuleMember -Function Ping-GOWebService