ContainerHandling/Get-NavContainerSession.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
66
67
68
69
70
71
72
73
<#
 .Synopsis
  Get (or create) a PSSession for a NAV/BC Container
 .Description
  Checks the session cache for an existing session. If a session exists, it will be reused.
  If no session exists, a new session will be created.
 .Parameter containerName
  Name of the container for which you want to create a session
 .Parameter silent
  Include the silent switch to avoid the welcome text
 .Example
  $session = Get-NavContainerSession -containerName navserver
  PS C:\>Invoke-Command -Session $session -ScriptBlock { Set-NavServerInstance -ServerInstance $ServerInstance -restart }
#>

function Get-NavContainerSession {
    [CmdletBinding()]
    Param (
        [string] $containerName = "navserver",
        [switch] $silent
    )

    Process {
        $containerId = Get-NavContainerId -containerName $containerName

        if ($sessions.ContainsKey($containerId)) {
            $session = $sessions[$containerId]
            try {
                $ok = Invoke-Command -Session $session -ScriptBlock { $true }
            }
            catch {
                Remove-PSSession -Session $session
                $sessions.Remove($containerId)
            }
        }
        if (!($sessions.ContainsKey($containerId))) {
            $session = New-PSSession -ContainerId $containerId -RunAsAdministrator
            Invoke-Command -Session $session -ScriptBlock { Param([bool]$silent)

                $ErrorActionPreference = 'Stop'
                $runPath = "c:\Run"
                $myPath = Join-Path $runPath "my"

                function Get-MyFilePath([string]$FileName)
                {
                    if ((Test-Path $myPath -PathType Container) -and (Test-Path (Join-Path $myPath $FileName) -PathType Leaf)) {
                        (Join-Path $myPath $FileName)
                    } else {
                        (Join-Path $runPath $FileName)
                    }
                }

                . (Get-MyFilePath "prompt.ps1") -silent:$silent | Out-Null
                . (Get-MyFilePath "ServiceSettings.ps1") | Out-Null
                . (Get-MyFilePath "HelperFunctions.ps1") | Out-Null

                $txt2al = ""
                if ($roleTailoredClientFolder) {
                    $txt2al = Join-Path $roleTailoredClientFolder "txt2al.exe"
                    if (!(Test-Path $txt2al)) {
                        $txt2al = ""
                    }
                }

                Set-Location $runPath
            } -ArgumentList $silent
            $sessions.Add($containerId, $session)
        }
        $sessions[$containerId]
    }
}
Set-Alias -Name Get-BCContainerSession -Value Get-NavContainerSession
Export-ModuleMember -Function Get-NavContainerSession -Alias Get-BCContainerSession