Api/Get-NavContainerApiCompanyId.ps1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
<#
 .Synopsis
  Invoke Api in Container
 .Description
  Invoke an Api in a Container.
 .Parameter containerName
  Name of the container in which you want to invoke an api
 .Parameter tenant
  Name of the tenant in which context you want to invoke an api
 .Parameter Credential
  Credentials for the user making invoking the api (do not specify if using Windows auth)
 .Parameter CompanyName
  CompanyName for which you want to get the Company Id (leave empty to get company Id for the default company)
 .Example
  $companyId = Get-NavContainerApiCompanyId -containerName $containerName -credential $credential
 .Example
  $companyId = Get-NavContainerApiCompanyId -containerName $containerName -credential $credential -CompanyName 'CRONUS International Ltd.'
#>

function Get-NavContainerApiCompanyId {
    Param (
        [Parameter(Mandatory=$true)]
        [string] $containerName, 
        [Parameter(Mandatory=$false)]
        [string] $tenant = "default",
        [Parameter(Mandatory=$false)]
        [PSCredential] $credential = $null,
        [Parameter(Mandatory=$false)]
        [string] $CompanyName = ""
    )

    if (!($CompanyName)) {

        $customConfig = Get-NavContainerServerConfiguration -ContainerName $containerName
    
        if ($credential) {
            $username = $credential.UserName
        } else {
            $username = whoami
        }
        
        $user = Get-NavContainerNavUser -containerName $containerName -tenant $tenant | Where-Object { $_.Username -eq $Username }
        if (!($CompanyName)) {
            if ($user) {
                $CompanyName = $user.Company
            }
        }
        if (!($CompanyName)) {
            $CompanyName = $customConfig.ServicesDefaultCompany
        }
        if (!($CompanyName)) {
            $Company = Invoke-ScriptInNavContainer -containerName $containerName -scriptblock { Param($tenant)
                Get-NavCompany -ServerInstance $serverInstance -tenant default
            } -argumentList $tenant | Where-Object { $_ -isnot [System.String] }
            $CompanyName = $Company | Select-Object -First 1 -ExpandProperty CompanyName
        }
    }

    $companyFilter = [Uri]::EscapeDataString("name eq '$CompanyName'")
    
    $result = Invoke-NavContainerApi -containerName $containerName -tenant $tenant -APIVersion "beta" -Query "companies?`$filter=$companyFilter" -credential $credential
    $result.value | Select-Object -First 1 -ExpandProperty id
}
Set-Alias -Name Get-BCContainerApiCompanyId -Value Get-NavContainerApiCompanyId
Export-ModuleMember -Function Get-NavContainerApiCompanyId -Alias Get-BCContainerApiCompanyId