Private/Import-AtwsCmdLet.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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
<#
 
.COPYRIGHT
Copyright (c) ECIT Solutions AS. All rights reserved. Licensed under the MIT license.
See https://github.com/ecitsolutions/Autotask/blob/master/LICENSE.md for license information.
 
#>

Function Import-AtwsCmdLet {
    <#
        .SYNOPSIS
            This function generates and imports Powershell functions tailored to the input.
        .DESCRIPTION
            This function takes custom PSObjects generated by function Get-AtwsFieldInfo and
            uses them to generate Powershell code for all entities in the input, converts them
            to [ScriptBlock] and imports them in the module.
        .INPUTS
            [PSObject[]]
        .OUTPUTS
            Powershell functions
        .EXAMPLE
            Import-AtwsCmdLet
            Gets all dynamic entities from Get-AtwsFieldInfo and generates and imports functions
            for them all.
        .NOTES
            NAME: Import-AtwsCmdLet
        .LINK
            Get-AtwsFieldInfo
 
  #>

    [CmdLetBinding(
        SupportsShouldProcess = $true,
        ConfirmImpact = 'Medium'
    )]
    Param(
        [PSObject[]]
        $Entities = $(Get-AtwsFieldInfo -Dynamic)
    )
  
    begin { 

        # Enable modern -Debug behavior
        if ($PSCmdlet.MyInvocation.BoundParameters['Debug'].IsPresent) { $DebugPreference = 'Continue' }  
              
        Write-Debug -Message ('{0}: Start of function.' -F $MyInvocation.MyCommand.Name)

        # Prepare parameters for @splatting
        $progressId = 2
        $progressParameters = @{
            Activity = 'Creating and importing functions for all Autotask entities with picklists.'
            Id       = $progressId
        }
        
        # The path to a users personal cache folder
        $rootPath = $Script:Atws.DynamicCache

        # Make sure directory exists
        if (-not (Test-Path "$rootPath")) {
            $null = New-Item -Path "$rootPath" -ItemType Directory -Force
        }
    
    } 
  
    process {
            
        # Prepare Index for progressbar
        $index = 0
    
        Write-Verbose -Message ('{0}: Creating functions for {1} entities' -F $MyInvocation.MyCommand.Name, $Entities.count) 
        
        foreach ($cacheEntry in $Entities.GetEnumerator()) {
            # EntityInfo()
            $entity = $cacheEntry.Value.EntityInfo
      
            Write-Debug -Message ('{0}: Creating functions for entity {1}' -F $MyInvocation.MyCommand.Name, $entity.Name) 
      
            # Calculating progress percentage and displaying it
            $index++
            $percentComplete = $index / $Entities.Count * 100
      
            # Add parameters for @splatting
            $progressParameters['percentComplete'] = $percentComplete
            $progressParameters['Status'] = 'Entity {0}/{1} ({2:n0}%)' -F $index, $Entities.Count, $percentComplete
            $progressParameters['CurrentOperation'] = 'Importing {0}' -F $entity.Name
      
            Write-AtwsProgress @progressParameters
      
            $caption = $MyInvocation.MyCommand.Name
            $verboseDescription = '{0}: Creating and Invoking functions for entity {1}' -F $caption, $entity.Name
            $verboseWarning = '{0}: About to create and Invoke functions for entity {1}. Do you want to continue?' -F $caption, $entity.Name
       
            $functionDefinition = Get-AtwsfunctionDefinition -Entity $entity -FieldInfo $cacheEntry.Value.FieldInfo
        
            if ($PSCmdlet.ShouldProcess($verboseDescription, $verboseWarning, $caption)) { 
        
                foreach ($function in $functionDefinition.GetEnumerator()) {
                    # Set path to powershell script file in user cache
                    $filePath = Join-Path $rootPath ('{0}.ps1' -f $function.Key)
          
                    # Import the updated function
                    . ([ScriptBlock]::Create($function.Value))
          
                    # Export the module member
                    Export-ModuleMember -Function $function.Key
          
                    # Write the function to disk for faster load later
                    Set-Content -Path $filePath -Value $function.Value -Force -Encoding UTF8           
                }
            }
        }
        
        if ($progressParameters['CurrentOperation']) { 
            Write-AtwsProgress @progressParameters -Completed
        }        

    }

    end {
        Write-Debug -Message ('{0}: Imported {1} dynamic functions' -F $MyInvocation.MyCommand.Name, $index)
    }
}