DSCResources/TYConsulting_cPowerShellModuleManagement/TYConsulting_cPowerShellModuleManagement.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
Function Get-TargetResource
{
    [CmdletBinding()]
    [OutputType([System.Array])]
    param(
      [ValidateSet('Present','Absent')]
  [System.String]
  $Ensure = 'Present',

  [parameter(Mandatory = $true, HelpMessage="Enter the PowerShell module name. Enter 'All' to include all modules in the repository.")]
      [ValidateNotNullOrEmpty()]
  [System.String]
  $PSModuleName,

  [parameter(Mandatory = $false)]
      [ValidateNotNullOrEmpty()]
  [System.Version]
  $PSModuleVersion,

  [parameter(Mandatory = $true,HelpMessage='Enter PowerShell Repository Name')]
      [ValidateNotNullOrEmpty()]
  [System.String]
  $RepositoryName,

  [parameter(Mandatory = $false)]
      [ValidateNotNullOrEmpty()]
      [ValidateRange(0,23)]
  [System.Int32]
  $MaintenanceStartHour,

  [parameter(Mandatory = $false)]
      [ValidateNotNullOrEmpty()]
      [ValidateRange(0,59)]
  [System.Int32]
  $MaintenanceStartMinute,

  [parameter(Mandatory = $false)]
      [ValidateNotNullOrEmpty()]
  [System.Int32]
  $MaintenanceLengthMinute
    )
    $arrModules = @()
    
    $parms = @{
      Repository = $RepositoryName
    }
    If ($PSModuleName -ine 'all')
    {
      $parms.Add('Name', $PSModuleName)
      If ($PSBoundParameters.ContainsKey('PSModuleVersion'))
      {
        $parms.Add('RequiredVersion', $PSModuleVersion)
        Write-Verbose ("Getting module '{0}' version '{1}' from repository '{2}'." -f $PSModuleName, $PSModuleVersion, $RepositoryName)
      } else {
        Write-Verbose ("Getting the latest version of module '{0}' from repository '{1}'." -f $PSModuleName, $RepositoryName)
      }
    } else {
      Write-Verbose ("Getting all modules from repository '{0}'." -f $RepositoryName)
    }

    $ModulesInRepo = PowerShellGet\Find-Module @parms -ErrorVariable ev -ErrorAction SilentlyContinue
    Write-Verbose "Modules found in repository: $($ModulesInRepo.Count)"
    Foreach ($ModuleInRepo in $ModulesInRepo)
    {
      Write-Verbose ("Checking module '{0}' version '{1}'." -f $ModuleInRepo.Name, $ModuleInRepo.Version.Tostring())
      $localModule = Get-Module -Name $($ModuleInRepo.Name) -ListAvailable | Where-Object {$_.version -eq $($ModuleInRepo.Version)}
      $objProperties = @{
        Name = $ModuleInRepo.Name
        Version = $ModuleInRepo.Version
      }
      If ($localModule)
      {
        Write-Verbose ("Module '{0}' version '{1}' is Present." -f $ModuleInRepo.Name, $ModuleInRepo.Version.Tostring())
        $objProperties.Add('Ensure', 'Present')
      } else {
        Write-Verbose ("Module '{0}' version '{1}' is Absent." -f $ModuleInRepo.Name, $ModuleInRepo.Version.Tostring())
        $objProperties.Add('Ensure', 'Absent')
      }
      $objLocalModule = new-object PSObject -Property $objProperties
      $arrModules +=$objLocalModule
    }
    ,$arrModules
}

Function Set-TargetResource
{
    [CmdletBinding()]
    param(
      [ValidateSet('Present','Absent')]
  [System.String]
  $Ensure = 'Present',

  [parameter(Mandatory = $true, HelpMessage="Enter the PowerShell module name. Enter 'All' to include all modules in the repository.")]
      [ValidateNotNullOrEmpty()]
  [System.String]
  $PSModuleName,

  [parameter(Mandatory = $false)]
      [ValidateNotNullOrEmpty()]
  [System.Version]
  $PSModuleVersion,

  [parameter(Mandatory = $true,HelpMessage='Add help message for user')]
      [ValidateNotNullOrEmpty()]
  [System.String]
  $RepositoryName,

  [parameter(Mandatory = $false)]
      [ValidateNotNullOrEmpty()]
      [ValidateRange(0,23)]
  [System.Int32]
  $MaintenanceStartHour,

  [parameter(Mandatory = $false)]
      [ValidateNotNullOrEmpty()]
      [ValidateRange(0,59)]
  [System.Int32]
  $MaintenanceStartMinute,

  [parameter(Mandatory = $false)]
      [ValidateNotNullOrEmpty()]
  [System.Int32]
  $MaintenanceLengthMinute
    )
    Write-Verbose "Getting Install-Module command details."
    $InstallModuleCmdInfo = Get-command Install-Module

    Write-Output ("Getting modules from repository '{0}'." -f $RepositoryName)
    $parms = @{
      Repository = $RepositoryName
    }
    If ($PSModuleName -ine 'all')
    {
      $parms.Add('Name', $PSModuleName)
      If ($PSBoundParameters.ContainsKey('PSModuleVersion'))
      {
        $parms.Add('RequiredVersion', $PSModuleVersion)
      }
    }
    #check if Installation / Uninstallation can be actioned at this point of time
    If ($PSBoundParameters.ContainsKey('MaintenanceStartHour') -and $PSBoundParameters.ContainsKey('MaintenanceStartMinute') -and $PSBoundParameters.ContainsKey('MaintenanceLengthMinute'))
    {
      $bOKtoAction = Validate-MaintenanceWindow -MaintenanceStartHour $MaintenanceStartHour -MaintenanceStartMinute $MaintenanceStartMinute -MaintenanceLengthMinute $MaintenanceLengthMinute
    } else {
      #If maintenance window is not specified, set to true
      Write-Verbose 'Maintenance window is not specified. It will be ignored.'
      $bOKtoAction = $true
    }
    $ModulesInRepo = PowerShellGet\Find-Module @parms -ErrorVariable ev -ErrorAction SilentlyContinue

    Foreach ($ModuleInRepo in $ModulesInRepo)
    {
      $localModule = Get-Module -Name $($ModuleInRepo.Name) -ListAvailable | Where-Object {$_.version -eq $($ModuleInRepo.Version)}
      If ($localModule)
      {
        Write-Verbose ("Module {0} version '{1}' is already installed." -f $ModuleInRepo.Name, $ModuleInRepo.Version)
        If ($Ensure -ieq 'absent')
        {
          If ($PSBoundParameters.ContainsKey('PSModuleVersion'))
          {
            #Make sure uninstallation is not actioned outside of the maintenance window
            if ($bOKtoAction)
            {
              Write-Verbose ("Uinstalling Module {0} version '{1}'." -f $ModuleInRepo.Name, $ModuleInRepo.Version)
              $UninstallModule = PowerShellGet\Uninstall-Module -Name $ModuleInRepo.Name -RequiredVersion $ModuleInRepo.Version -Force -ErrorVariable ev -ErrorAction SilentlyContinue
            } else {
              Write-Verbose ("Module {0} version '{1}' will not be uninstalled at this time because it is out side of configured maintenance window." -f $ModuleInRepo.Name, $ModuleInRepo.Version)
            }
          } else {
            #Make sure uninstallation is not actioned outside of the maintenance window
            if ($bOKtoAction)
            {
              Write-Verbose ("Uinstalling all versions of Module {0}." -f $ModuleInRepo.Name)
              $UninstallModule = PowerShellGet\Uninstall-Module -Name $ModuleInRepo.Name -AllVersions -Force -ErrorVariable ev -ErrorAction SilentlyContinue
            } else {
              Write-Verbose ("All versions of Module {0} will not be uninstalled at this time because it is outside of configured maintenance window." -f $ModuleInRepo.Name)
            }
          }
        }
      } else {
        Write-Verbose ("Module {0} version '{1}' is not installed." -f $ModuleInRepo.Name, $ModuleInRepo.Version)
        if ($Ensure -ieq 'present')
        {
          if ($bOKtoAction)
          {
            Write-Verbose ("Installing Module {0} version '{1}' now." -f $ModuleInRepo.Name, $ModuleInRepo.Version)
            If ($InstallModuleCmdInfo.Parameters.containskey("AllowClobber"))
            {
              Write-Verbose "Installing the module using Install-Module cmdlet with -AllowClobber switch."
              $InstallModule = PowerShellGet\Install-Module -Name $($ModuleInRepo.Name) -RequiredVersion $($ModuleInRepo.Version) -Repository $RepositoryName -Force -Scope AllUsers -AllowClobber
            } else {
              Write-Verbose "Installing the module using Install-Module cmdlet without -AllowClobber switch."
              $InstallModule = PowerShellGet\Install-Module -Name $($ModuleInRepo.Name) -RequiredVersion $($ModuleInRepo.Version) -Repository $RepositoryName -Force -Scope AllUsers
            }
            
          } else {
            Write-Verbose ("Module {0} version '{1}' will not be installed at this time because it is outside of configured maitnenance window." -f $ModuleInRepo.Name, $ModuleInRepo.Version)
          }
        }        
      }
    }

    If(!(Test-TargetResource @PSBoundParameters))
    {
        throw 'Set-TargetResouce failed'
    }
}

Function Test-TargetResource
{
    [CmdletBinding()]
    [OutputType([System.Boolean])]
    param(
      [ValidateSet('Present','Absent')]
  [System.String]
  $Ensure = 'Present',

  [parameter(Mandatory = $true, HelpMessage="Enter the PowerShell module name. Enter 'All' to include all modules in the repository.")]
      [ValidateNotNullOrEmpty()]
  [System.String]
  $PSModuleName,

  [parameter(Mandatory = $false)]
      [ValidateNotNullOrEmpty()]
  [System.Version]
  $PSModuleVersion,

  [parameter(Mandatory = $true)]
      [ValidateNotNullOrEmpty()]
  [System.String]
  $RepositoryName,

  [parameter(Mandatory = $false)]
      [ValidateNotNullOrEmpty()]
      [ValidateRange(0,23)]
  [System.Int32]
  $MaintenanceStartHour,

  [parameter(Mandatory = $false)]
      [ValidateNotNullOrEmpty()]
      [ValidateRange(0,59)]
  [System.Int32]
  $MaintenanceStartMinute,

  [parameter(Mandatory = $false)]
      [ValidateNotNullOrEmpty()]
  [System.Int32]
  $MaintenanceLengthMinute
    )
    $arrModules = Get-TargetResource @PSBoundParameters
    $result = $true
    Foreach ($item in $arrModules)
    {
      Write-Verbose "$($item.Name) is currently $($item.Ensure), desired configuration is $ensure."
      if ($item.Ensure -ine $Ensure)
      {
        $result = $false
      }
    }
    $result
}

Function Validate-MaintenanceWindow
{
  [CmdletBinding()]
  [OutputType([System.Boolean])]
  Param (
[parameter(Mandatory = $true)]
    [ValidateNotNullOrEmpty()]
    [ValidateRange(0,24)]
[System.Int32]
$MaintenanceStartHour,

[parameter(Mandatory = $true)]
    [ValidateNotNullOrEmpty()]
    [ValidateRange(0,60)]
[System.Int32]
$MaintenanceStartMinute,

[parameter(Mandatory = $true)]
    [ValidateNotNullOrEmpty()]
[System.Int32]
$MaintenanceLengthMinute
  )

  $MaintenanceStartTime = Get-Date -Hour $MaintenanceStartHour -Minute $MaintenanceStartMinute
  $now = Get-Date
  $MaintenanceEndTime = $MaintenanceStartTime.AddMinutes($MaintenanceLengthMinute)
  Write-Verbose "Maintenance Window Start Time: $($MaintenanceStartTime.Tostring())"
  Write-Verbose "Maintenance Window End Time: $($MaintenanceEndTime.Tostring())"
  #Check if the current datetime is within the maintenance window.
  If ($MaintenanceStartTime -le $now -and $MaintenanceEndTime -gt $now)
  {
    $bWithinMaintWindow = $true
  } else {
    $bWithinMaintWindow = $false
  }

  $bWithinMaintWindow
}
Export-ModuleMember -Function *-TargetResource