LocalDev.psm1

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
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
$Script:LocalAutomationVariable = @{}
<#
.SYNOPSIS
    Returns a scriptblock that, when dot-sourced, will import a workflow and all its dependencies.
 
.DESCRIPTION
    Import-Workflow is a helper function to resolve dependencies of a given workflow. It must be
    invoked with a very specific syntax in order to import workflows into your current session.
    See the example.
 
.PARAMETER WorkflowName
    The name of the workflow to import.
 
.PARAMETER Path
    The path containing all ps1 files to search for workflow dependencies.
 
.EXAMPLE
    PS > . (Import-Workflow Test-Workflow)
#>

function Import-Workflow 
{
    param(
        [Parameter(Mandatory=$True)]  [String] $WorkflowName,
        [Parameter(Mandatory=$False)] [String] $Path = $env:AutomationWorkflowPath
    )

    # TODO: Make $CompileStack a more appropriate data structure.
    # We're not really using the stack functionality at all. In fact,
    # it was buggy. :-(
    $CompileStack = New-Object -TypeName 'System.Collections.Stack'
    $TokenizeStack = New-Object -TypeName 'System.Collections.Stack'
    $DeclaredCommands = Find-DeclaredCommand -Path $Path
    $BaseWorkflowPath = $DeclaredCommands[$WorkflowName].Path
    $Stacked = @{$BaseWorkflowPath = $True}
    $TokenizeStack.Push($BaseWorkflowPath)
    $CompileStack.Push($BaseWorkflowPath)
    while ($TokenizeStack.Count -gt 0) 
    {
        $ScriptPath = $TokenizeStack.Pop()
        $Tokens = [System.Management.Automation.PSParser]::Tokenize((Get-Content -Path $ScriptPath), [ref] $null)
        $NeededCommands = ($Tokens | Where-Object -FilterScript { $_.Type -eq 'Command' }).Content
        foreach ($Command in $NeededCommands) 
        {
            $NeededScriptPath = $DeclaredCommands[$Command].Path
            # If $NeededScriptPath is $null, we didn't find it when we searched declared
            # commands in the runbook path. We'll assume that is okay and that the command
            # is provided by some other means (e.g. a module import)
            if (($NeededScriptPath -ne $null) -and (-not $Stacked[$NeededScriptPath])) 
            {
                $TokenizeStack.Push($NeededScriptPath)
                $CompileStack.Push($NeededScriptPath)
                $Stacked[$NeededScriptPath] = $True
            }
        }
    }
    $WorkflowDefinitions = ($CompileStack | foreach { (Get-Content -Path $_) }) -join "`n"
    $ScriptBlock = [ScriptBlock]::Create($WorkflowDefinitions)
    return $ScriptBlock
}

<#
.SYNOPSIS
    Returns the named automation variable, referencing local JSON files to find values.
 
.PARAMETER Name
    The name of the variable to retrieve.
#>

Function Get-AutomationVariable
{
    Param(
        [Parameter(Mandatory=$True)]
        [String]
        $Name 
    )
    
    If(-not $Script:LocalAutomationVariable.ContainsKey($Name))
    {
        Update-LocalAutomationVariable
        If(-not $Script:LocalAutomationVariable.ContainsKey($Name))
        {
            Write-Warning -Message "Couldn't find variable $Name" -WarningAction 'Continue'
            Throw-Exception -Type 'VariableDoesNotExist' `
                            -Message "Couldn't find variable $Name" `
                            -Property @{
                'Variable' = $Name;
            }
        }
    }
    Return ($Script:LocalAutomationVariable[$Name]).Value
}
function Update-LocalAutomationVariable
{
    param()

    Write-Verbose -Message 'Updating variables in memory'
    $FilesToProcess = (Get-ChildItem -Path $env:AutomationGlobalsPath -Include '*.json' -Recurse).FullName
    Read-SmaJSONVariables -Path $FilesToProcess
}

<#
.SYNOPSIS
    Processes an JSON file, caching any variables it finds.
 
.PARAMETER Path
    The JSON files that should be processed.
#>

Function Read-SmaJSONVariables
{
    Param(
        [Parameter(Mandatory=$True)]
        [AllowNull()]
        [String[]]
        $Path
    )

    $Script:LocalAutomationVariable = @{}
    ForEach($_Path in $Path)
    {
        Try
        {
            $JSON = ConvertFrom-JSON -InputObject ((Get-Content -Path $_Path) -as [String])
        }
        Catch
        {
            Write-Warning -Message "Could not process [$_Path] - variables from that file will not be available" -WarningAction 'Continue'
            Write-Warning -Message "Does [$_Path] contain malformed JSON?" -WarningAction 'Continue'
            Write-Exception -Exception $_ -Stream 'Warning'
        }
        if(-not (Test-IsNullOrEmpty $JSON.Variables))
        {
            ForEach($VariableName in ($JSON.Variables | Get-Member -MemberType NoteProperty).Name)
            {
                $Var = $JSON.Variables."$VariableName"
                $retVar = New-Object -TypeName 'PSObject' -Property @{ 'Name' = $VariableName; 'Value' = $var.Value }
                $Script:LocalAutomationVariable[$VariableName] = $retVar
            }
        }
    }
}
<#
    .Synopsis
        Creates a variable in a json file. When this is commited these
        variables will be created in SMA through continuous integration
 
    .Parameter VariableFilePath
        The path to the file to store this variable in. If not passed it is
        assumed you want to store it in the same file you did last time
 
    .Parameter Name
        The name of the variable to create.
        Variables will be named in the format
 
        Prefix-Name
 
    .Parameter Prefix
        The prefix of the variable to create. If not passed it will default
        to the name of the variable file you are storing it in
        Variables will be named in the format
 
        Prefix-Name
     
    .Parameter Value
        The value to store in the object. If a non primative is passed it
        will be converted into a string using convertto-json
 
    .Parameter Description
        The description of the variable to store in SMA
 
    .isEncrypted
        A boolean flag representing if this value should be encrypted in SMA
 
#>

Function Set-AutomationVariable
{
    Param(
        [Parameter(Mandatory=$True)]  $Name,
        [Parameter(Mandatory=$True)]  $Value,
        [Parameter(Mandatory=$False)] $Prefix = [System.String]::Empty,
        [Parameter(Mandatory=$False)] $Description = [System.String]::Empty,
        [Parameter(Mandatory=$False)] $isEncrypted = $False
    )
    if(-not $Prefix)
    {
        $Prefix = $Name.Split('-')[0]
    }
    else
    {
        $Name = "$Prefix-$Name"
    }
    $SettingsFilePath = "$($Env:AutomationGlobalsPath)\$($Prefix).json"
    if(-not (Test-Path -Path $SettingsFilePath))
    {
        New-Item -ItemType File `
                 -Path $settingsFilePath
    }

    $SettingsVars = ConvertFrom-JSON -InputObject ((Get-Content -Path $SettingsFilePath) -as [String])
    if(-not $SettingsVars) { $SettingsVars = @{} }
    else
    {
        $SettingsVars = ConvertFrom-PSCustomObject $SettingsVars
    }
    if(-not $SettingsVars.ContainsKey('Variables'))
    {
        $SettingsVars.Add('Variables',@{}) | out-null
    }
    
    if($Value.GetType().Name -notin @('Int32','String','DateTime'))
    {
        $Value = ConvertTo-JSON $Value -Compress
    }

    if($SettingsVars.Variables.GetType().name -eq 'PSCustomObject') { $SettingsVars.Variables = ConvertFrom-PSCustomObject $SettingsVars.Variables }
    if($SettingsVars.Variables.ContainsKey($Name))
    {
        $SettingsVars.Variables."$Name".Value = $Value
        if($Description) { $SettingsVars.Variables."$Name".Description = $Description }
        if($Encrypted)   { $SettingsVars.Variables."$Name".Encrypted   = $Encrypted   }
    }
    else
    {
        $SettingsVars.Variables.Add(
            $Name, @{ 
                'Value' = $Value ;
                'Description' = $Description ;
                'isEncrypted' = $isEncrypted 
            }
        )
    }
    
    Set-Content -Path $SettingsFilePath -Value (ConvertTo-JSON $SettingsVars) -Encoding UTF8
    Read-SmaJSONVariables $SettingsFilePath
}

Function Remove-AutomationVariable
{
    Param(
        [Parameter(Mandatory=$True)]
        [string]        
        $Name,

        [Parameter(Mandatory=$False)]
        [string]
        $Prefix
    )
    if(-not $Prefix)
    {
        $Prefix = $Name.Split('-')[0]
    }
    else
    {
        $Name = "$Prefix-$Name"
    }
    $SettingsFilePath = "$($Env:AutomationGlobalsPath)\$($Prefix).json"
    if(-not (Test-Path $SettingsFilePath))
    {
        Throw-Exception -Type 'SettingsFileNotFound' `
                        -Message 'Could not find the settings file for the target variable.' `
                        -Property @{
                            'SettingsFilePath' = $SettingsFilePath ;
                            'VariableName' = $Name ;
                            'VariablePrefix' = $Prefix ;
                        }
    }
    $SettingsVars = ConvertFrom-JSON -InputObject ((Get-Content -Path $SettingsFilePath) -as [String])
    if(-not $SettingsVars) { $SettingsVars = @{} }
    else
    {
        $SettingsVars = ConvertFrom-PSCustomObject $SettingsVars
    }
    if(-not $SettingsVars.ContainsKey('Variables'))
    {
        $SettingsVars.Add('Variables',@{}) | out-null
    }

    if($SettingsVars.Variables.GetType().name -eq 'PSCustomObject') { $SettingsVars.Variables = ConvertFrom-PSCustomObject $SettingsVars.Variables }
    if($SettingsVars.Variables.ContainsKey($Name))
    {
        $SettingsVars.Variables.Remove($Name)
        Set-Content -Path $SettingsFilePath -Value (ConvertTo-JSON $SettingsVars) -Encoding UTF8
        Read-SmaJSONVariables $SettingsFilePath
    }
    else
    {
        Write-Warning (New-Exception -Type 'Variable Not found' `
                                     -Message 'The variable was not found in the current variable file.' `
                                     -Property @{ 'VariableName' = $Name ;
                                                  'CurrentFilePath' = $SettingsFilePath ;
                                                  'VariableJSON' = $SettingsVars }) `
                      -WarningAction 'Continue'
    }
}
Workflow Get-AutomationPSCredential 
{
    [OutputType([System.Management.Automation.PSCredential])]
    param(
        [Parameter(Mandatory=$true)]
        [string]
        $Name
    )

    Try
    {
        $Val = (Get-PasswordVaultCredential -UserName $Name -WithPassword)
        Write-Verbose -Message "Credential [$Name] found in PasswordVault"
    }
    Catch
    {
        Throw-Exception -Type 'CredentialNotFound' `
                        -Message 'Could not find credential. Please set it up in the local password vault using Set-PasswordVaultCredential' `
                        -Property @{ 
                            'Name' = $Name 
                        }
    }
    $SecurePassword = $Val.Password | ConvertTo-SecureString -asPlainText -Force
    $Credential = New-Object -TypeName System.Management.Automation.PSCredential($Val.Username, $SecurePassword)
    Return $Credential -as [System.Management.Automation.PSCredential]
}

Function Set-AutomationSchedule
{
    Param(
        [Parameter(Mandatory=$True)]
        [String]
        $Name,

        [Parameter(Mandatory=$False)]
        [String]
        $Prefix = [System.String]::Emptpy,
        
        [Parameter(Mandatory=$False)]
        [String]
        $Description = [System.String]::Emptpy,

        [Parameter(Mandatory=$False)]
        [DateTime]
        $NextRun = $null,

        [Parameter(Mandatory=$False)]
        [DateTime]
        $ExpirationTime = $null,

        [Parameter(Mandatory=$False)]
        [Int]
        $DayInterval = $null,

        [Parameter(Mandatory=$False)]
        [String]
        $RunbookName = [System.String]::Emptpy,

        [Parameter(Mandatory=$False)]
        [HashTable]
        $Parameter = @{}
    )
    if(-not $Prefix)
    {
        $Prefix = $Name.Split('-')[0]
    }
    else
    {
        $Name = "$Prefix-$Name"
    }
    $SettingsFilePath = "$($Env:AutomationGlobalsPath)\$($Prefix).json"
    if(-not (Test-Path -Path $SettingsFilePath))
    {
        New-Item -ItemType File `
                 -Path $settingsFilePath
    }

    $SettingsVars = ConvertFrom-JSON -InputObject ((Get-Content -Path $SettingsFilePath) -as [String])
    if(-not $SettingsVars) { $SettingsVars = @{} }
    else
    {
        $SettingsVars = ConvertFrom-PSCustomObject $SettingsVars
    }

    if(-not $SettingsVars.ContainsKey('Schedules'))
    {
        $SettingsVars.Add('Schedules',@{}) | out-null
    }
    if($SettingsVars.Schedules.GetType().name -eq 'PSCustomObject') { $SettingsVars.Schedules = ConvertFrom-PSCustomObject $SettingsVars.Schedules }
    if($SettingsVars.Schedules.ContainsKey($Name))
    {
        if($Description)    { $SettingsVars.Schedules."$Name".Description    = $Description }
        if($NextRun)        { $SettingsVars.Schedules."$Name".NextRun        = $NextRun }
        if($ExpirationTime) { $SettingsVars.Schedules."$Name".ExpirationTime = $ExpirationTime }
        if($DayInterval)    { $SettingsVars.Schedules."$Name".DayInterval    = $DayInterval }
        if($RunbookName)    { $SettingsVars.Schedules."$Name".RunbookName    = $RunbookName }
        if($Parameter)      { $SettingsVars.Schedules."$Name".Parameter      = $(ConvertTo-Json $Parameter) }
    }
    else
    {
        if(-not $ExpirationTime -or
           -not $NextRun -or
           -not $DayInterval -or
           -not $RunbookName )
        {
            Throw-Exception -Type 'MinimumNewParametersNotFound' `
                            -Message 'The minimum set of input parameters for creating a new schedule was not supplied. Look at nulls' `
                            -Property @{ 'Name' = $Name ;
                                         'ExpirationTime' = $ExpirationTime ;
                                         'NextRun' = $NextRun ;
                                         'DayInterval' = $DayInterval ;
                                         'RunbookName' = $RunbookName ; }
        }

        $SettingsVars.Schedules.Add(
            $Name, @{ 
                'Description' = $Description ;
                'ExpirationTime' = $ExpirationTime -as [DateTime] ;
                'NextRun' = $NextRun -as [DateTime] ;
                'DayInterval' = $DayInterval ;
                'RunbookName' = $RunbookName ;
                'Parameter' = $(ConvertTo-JSON $Parameter)
            }
        )
    }
    
    Set-Content -Path $SettingsFilePath -Value (ConvertTo-JSON $SettingsVars) -Encoding UTF8
}
Function Remove-AutomationSchedule
{
    Param(
        [Parameter(Mandatory=$False)]
        $SettingsFilePath,

        [Parameter(Mandatory=$True)] 
        $Name,

        [Parameter(Mandatory=$False)]
        $Prefix
    )
    if(-not $Prefix)
    {
        $Prefix = $Name.Split('-')[0]
    }
    $SettingsFilePath = "$($Env:AutomationGlobalsPath)\$($Prefix).json"
    if(-not (Test-Path $SettingsFilePath))
    {
        Throw-Exception -Type 'SettingsFileNotFound' `
                        -Message 'Could not find the settings file for the target variable.' `
                        -Property @{
                            'SettingsFilePath' = $SettingsFilePath ;
                            'ScheduleName' = $Name ;
                            'SchedulePrefix' = $Prefix ;
                        }
    }
    $SettingsVars = ConvertFrom-JSON -InputObject ((Get-Content -Path $SettingsFilePath) -as [String])
    if(Test-IsNullOrEmpty $SettingsVars.Schedules)
    {
        Add-Member -InputObject $SettingsVars -MemberType NoteProperty -Value @() -Name Schedules
    }
    if(($SettingsVars.Schedules | Get-Member -MemberType NoteProperty).Name -Contains $Name)
    {
        $SettingsVars.Schedules = $SettingsVars.Schedules | Select-Object -Property * -ExcludeProperty $Name
        Set-Content -Path $SettingsFilePath -Value (ConvertTo-JSON $SettingsVars) -Encoding UTF8
    }
    else
    {
        Write-Warning (New-Exception -Type 'Schedule Not found' `
                                     -Message 'The schedule was not found in the current variable file. Try specifiying the file' `
                                     -Property @{ 'VariableName' = $Name ;
                                                  'CurrentFilePath' = $SettingsFilePath ;
                                                  'SettingsJSON' = $SettingsVars }) `
                      -WarningAction 'Continue'
    }
}
<#
    .Synopsis
        Fake for Set-AutomationActivityMetadata for local dev.
#>

Function Set-AutomationActivityMetadata
{
    Param([Parameter(Mandatory=$True)] $ModuleName,
          [Parameter(Mandatory=$True)] $ModuleVersion,
          [Parameter(Mandatory=$True)] $ListOfCommands)

    $Inputs = ConvertTo-JSON @{ 'ModuleName' = $ModuleName;
                                'ModuleVersion' = $ModuleVersion;
                                'ListOfCommands' = $ListOfCommands }
    Write-Verbose -Message "$Inputs"
}
Export-ModuleMember -Function * -Verbose:$false