vSphereDSCHelper.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
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
enum VmwFolderType {
    Yellow
    Blue
}

function Enable-PowerCLI
{
<#
.SYNOPSIS
  Load PowerCLI modules and PSSnapins
.DESCRIPTION
  This function will load all requested PowerCLI
  modules and PSSnapins.
  The function will, depending on the installed PowerCLI version,
  determine what needs to be loaded.
.NOTES
  Author: Luc Dekens
.PARAMETER Cloud
  Switch to indicate if the Cloud related cmdlets shall be loaded
.PARAMETER InitScript
  The PowerCLI PSSnapin have associated initialisation scripts.
  This switch will indicate if that script needs to be executed or not.
.EXAMPLE
  PS> Enable-PowerCLI
.EXAMPLE
  PS> Enable-PowerCLI -Cloud
#>


    [CmdletBinding()]
    param(
       [switch]$Cloud=$false,
       [switch]$InitScript=$true
    )

    Write-Verbose -Message "$(Get-Date) $($s = Get-PSCallStack;"Entering {0}" -f $s[0].FunctionName)" 

    $Global:PSDefaultParameterValues = @{
        "Get-View:Verbose"=$false
        "Add-PSSnapin:Verbose"=$false
        "Import-Module:Verbose"=$false
    }

    $PcliPssnapin = @{
    'VMware.VimAutomation.License' = @(2548067)
    'VMware.DeployAutomation' =@(2548067,3056836,3205540,3737840)
    'VMware.ImageBuilder' = @(2548067,3056836,3205540,3737840)
  }
   
    $PcliModule = @{
    'VMware.VimAutomation.Core' = @(2548067,3056836,3205540,3737840)
    'VMware.VimAutomation.Vds' = @(2548067,3056836,3205540,3737840)
    'VMware.VimAutomation.Cloud' = @(2548067,3056836,3205540,3737840)
    'VMware.VimAutomation.PCloud' = @(2548067,3056836,3205540,3737840)
    'VMware.VimAutomation.Cis.Core' = @(2548067,3056836,3205540,3737840)
    'VMware.VimAutomation.Storage' = @(2548067,3056836,3205540,3737840)
    'VMware.VimAutomation.HA' = @(2548067,3056836,3205540,3737840)
    'VMware.VimAutomation.vROps' = @(3056836,3205540,3737840)
    'VMware.VumAutomation' = @(3056836,3205540,3737840)
    'VMware.VimAutomation.License' = @(3056836,3205540,3737840)
  }
   
    # 32- or 64-bit process
    $procArch = (Get-Process -Id $Global:pid).StartInfo.EnvironmentVariables["PROCESSOR_ARCHITECTURE"]
    if($procArch -eq 'x86'){
      $regPath = 'HKLM:\Software\VMware, Inc.\VMware vSphere PowerCLI'
    }
    else{
      $regPath = 'HKLM:\Software\WOW6432Node\VMware, Inc.\VMware vSphere PowerCLI'
    }
     
    # Check if PowerCLI (regular or Tenant) is installed
    if(!(Test-Path -Path $regPath))
    {
      $regPath = $regPath.Replace('VMware vSphere PowerCLI','VMware vSphere PowerCLI for Tenants')
      if(!(Test-Path -Path $regPath))
      {
          Throw 'Can not find a PowerCLI installation!'       
      }
    }
     
    # Get build
    $buildKey = 'InstalledBuild'
    Try{
      $pcliBuild = Get-ItemProperty -Path $regPath -Name $buildKey |
          Select -ExpandProperty $buildKey -ErrorAction Stop
    }
    Catch{
      Throw "PowerCLI doesn't seem to be installed on this system!"
    }
    # Get installation path
    $installPathKey = 'InstallPath'
    Try{
      $pcliInstallPath = Get-ItemProperty -Path $regPath -Name $installPathKey |
          Select -ExpandProperty $installPathKey -ErrorAction Stop
    }
    Catch{
      Throw "PowerCLI doesn't seem to be installed on this system!"
    }
    # Load modules
    if($pcliBuild -ge 2548067)
    {
      $loadedModule = Get-Module -Name VMware* -ErrorAction SilentlyContinue | %{$_.Name}
      if($loadedModule -and $pcliBuild -ge 3737840)
      {
        $loadedModule = $loadedModule | where{$_ -notmatch 'Common$|SDK$'}
      }
     
      $targetModule = $PcliModule.GetEnumerator() | where{$_.Value -contains $pcliBuild} | %{$_.Key}
      $targetModule = $targetModule | where{$loadedModule -notcontains $_}
      if(!$Cloud)
      {
        $targetModule = $targetModule | where{$_ -notmatch 'Cloud'}
      }
      if($targetModule)
      {
        $targetModule | where{$loadedModule -notcontains $_.Name} | %{
          Import-Module -Name $_
        }
      }
    }
     
    # Load PSSnapin
    $loadedSnap = Get-PSSnapin -Name VMware* -ErrorAction SilentlyContinue -Verbose:$false | %{$_.Name}
    if($pcliBuild -ge 3737840)
    {
      $loadedSnap = $loadedSnap | where{$_ -notmatch 'Core$'}
    }
   
    $targetSnap = $PcliPssnapin.GetEnumerator() | where{$_.Value -contains $pcliBuild} | %{$_.Key}
    $targetSnap = $targetSnap | where{$loadedSnap -notcontains $_}
    if(!$Cloud)
    {
      $targetSnap = $targetSnap | where{$_ -notmatch 'Cloud'}
    }
    if($targetSnap)
    {
      $targetSnap | where{$loadedSnap -notcontains $_} | %{
        Add-PSSnapin -Name $_
   
        # Run initialisation script
        if($InitScript)
        {
          $filePath = "{0}Scripts\Initialize-{1}.ps1" -f $pcliInstallPath,$_.ToString().Replace(".", "_")
          if (Test-Path $filePath) {
            & $filePath
          }
        }
      }
    }

# $global:VerbosePreference = $SaveVerbosePreference

    Write-Verbose -Message "$(Get-Date) $($s = Get-PSCallStack;"Leaving {0}" -f $s[0].FunctionName)"    
}

function Connect-VmwVIServer
{
    [CmdletBinding()]
    [OutputType([System.String])]
    param(
        [string]$Server,
        [PSCredential]$Credential,
        [string]$Id
    )

    Write-Verbose -Message "$(Get-Date) $($s = Get-PSCallStack;"Entering {0}" -f $s[0].FunctionName)" 
    Write-Verbose -Message "$(Get-Date) Connect with credential $($Credential.UserName)"
    Write-Verbose -Message "$(Get-Date) SessionId $($Id)"

    Enable-PowerCLI
    
    Set-PowerCLIConfiguration -InvalidCertificateAction Ignore -DisplayDeprecationWarnings $false -Confirm:$false | Out-Null
    $srv = Connect-VIServer -Server $Server -Credential $Credential

    Write-Verbose -Message "$(Get-Date) Connected with credential $($Credential.UserName)"
    Write-Verbose -Message "$(Get-Date) $('Got session ID {0}' -f $srv.SessionId)"

    return $srv.SessionId

    Write-Verbose -Message "$(Get-Date) $($s = Get-PSCallStack;"Leaving {0}" -f $s[0].FunctionName)" 
}

function Get-VmwNodeFromPath
{
    [CmdletBinding()]
    [OutputType([System.Management.Automation.PSCustomObject])]
    param(
        [PSObject]$StartNode = (Get-View -Id (Get-View -Id ServiceInstance).Content.RootFolder),
        [String]$Path
    )

    function Get-NodeChild{
        param(
            [VMware.Vim.ManagedEntity]$Node
        )
    
        $hidden = 'vm','host','network','datastore','Resources'
        switch($Node){
            {$_ -is [VMware.Vim.Folder]}{
                if($Node.ChildEntity){
                    Get-View -Id $Node.ChildEntity
                }
            }
            {$_ -is [VMware.Vim.Datacenter]}{
                $all = @()
                $all += Get-View -Id $Node.VmFolder
                $all += Get-View -Id $Node.HostFolder
                $all += Get-View -Id $Node.DatastoreFolder
                $all += Get-View -Id $Node.NetworkFolder
                $all | %{
                    if($hidden -contains $_.Name){
                        Get-NodeChild -Node $_
                    }
                    else{
                        $_
                    }
                }
            }
            {$_ -is [VMware.Vim.ClusterComputeResource]}{
                $all = @()
                $all += Get-View -Id $Node.Host
                $all += Get-View -Id $Node.ResourcePool 
                $all = $all | %{
                    if($hidden -contains $_.Name){
                        Get-NodeChild -Node $_
                    }
                    else{
                        $_
                    }
                }
                $all
            }
            {$_ -is [VMware.Vim.ResourcePool]}{
                $all = @()
                if($Node.ResourcePool){
                    $all += Get-View -Id $Node.ResourcePool
                }
                if($Node.vm){
                    $all += Get-View -Id $Node.vm
                }
                $all
            }
            {$_ -is [VMware.Vim.DistributedVirtualSwitch]}{
                Get-View -Id $Node.Portgroup
            }
        }
    }

    Write-Verbose -Message "$(Get-Date) $($s = Get-PSCallStack;"Entering {0}" -f $s[0].FunctionName)" 
    Write-Verbose -Message "$(Get-Date) Start: $($StartNode.Name)" 
    Write-Verbose -Message "$(Get-Date) Path: $($Path)" 

    $found = $true
 
    # Loop through Path
    $node = @($StartNode)
    foreach($qualifier in $Path.TrimStart('/').Split('/',[StringSplitOptions]::RemoveEmptyEntries)){
        $nodeMatch = @($node) | %{
            Get-NodeChild -Node $_ | where{$_.Name -eq $qualifier}
        }
        if(!$nodeMatch){
            $found = $false
            $node = $null
            break
        }
        $node = $nodeMatch
    }
 
    Write-Verbose -Message "$(Get-Date) Nodes found $($node.Count)"
    Write-Verbose -Message "$(Get-Date) Nodes: $(($node | %{$_.Name}) -join '|')"

    if($node -eq $null){
        return New-Object PSObject -Property @{
            Path = $Path
            Found = $false
            Node = $null
        }
    }
    else{
        @($node) | %{
            return New-Object PSObject -Property @{
                Path = $Path
                Found = $true
                Node = $_
            }
        }
    }

    Write-Verbose -Message "$(Get-Date) $($s = Get-PSCallStack;"Leaving {0}" -f $s[0].FunctionName)" 
} 

function Test-VmwNodePath
{
    [CmdletBinding()]
    [OutputType([System.Boolean])]
    param(
        [PSObject]$StartNode = (Get-View -Id (Get-View -Id ServiceInstance).Content.RootFolder),
        [String]$Path
    )

    Write-Verbose -Message "$(Get-Date) $($s = Get-PSCallStack;"Entering {0}" -f $s[0].FunctionName)" 
    Write-Verbose -Message "$(Get-Date) Start: $($StartNode.Name)" 
    Write-Verbose -Message "$(Get-Date) Path: $($Path)" 

    $nodeObj = Get-VmwNodeFromPath -StartNode $StartNode -Path $Path
    
    return $nodeObj.Found

    Write-Verbose -Message "$(Get-Date) $($s = Get-PSCallStack;"Leaving {0}" -f $s[0].FunctionName)" 
}

function New-VmwFolder
{
    [CmdletBinding()]
    param(
        [VMware.Vim.ManagedEntity]$Parent,
        [String]$FolderName,
        [VmwFolderType]$FolderType
    )

    Write-Verbose -Message "$(Get-Date) $($s = Get-PSCallStack;"Entering {0}" -f $s[0].FunctionName)" 
    Write-Verbose -Message "$(Get-Date) Create a $($FolderType) folder, named $($FolderName), in $($Parent.Name) " 

    if($parent -is [VMware.Vim.Datacenter]){
       if($FolderType -eq [VmwFolderType]::Blue){
           $Parent.UpdateViewData('VmFolder')
           $leaf = Get-view -Id $parent.VmFolder -Property Name
       }
       else{
           $Parent.UpdateViewData('HostFolder')
           $leaf = Get-view -Id $parent.HostFolder -Property Name
       }
    }
    else{
       $leaf = $Parent
    }

    Write-Verbose -Message "$(Get-Date) Creating folder $($FolderName) at $($leaf.Name)" 
    $leaf.CreateFolder($FolderName) | Out-Null

    Write-Verbose -Message "$(Get-Date) $($s = Get-PSCallStack;"Leaving {0}" -f $s[0].FunctionName)" 
}

function Test-VmwFolderType
{
    [CmdletBinding()]
    [OutputType([System.Boolean])]
    param(
        [VMware.Vim.ManagedEntity]$Node,
        [VmwFolderType]$FolderType
    )
    
    Write-Verbose -Message "$(Get-Date) $($s = Get-PSCallStack;"Entering {0}" -f $s[0].FunctionName)" 
    Write-Verbose -Message "$(Get-Date) Testing if folder $($Node.Name) is $($FolderType)" 

    if($FolderType -eq [VmwFolderType]::Yellow)
    {
        $targetParent = 'host'
    }
    else
    {
        $targetParent = 'vm'
    }
    
    $si = Get-View -Id ServiceInstance
    $rootFolder = Get-View -Id $si.Content.RootFolder
    
    $foundType = $false
    if($Node.Parent -eq $rootFolder.MoRef -and $FolderType -eq [VmwFolderType]::Yellow){
        $foundType = $true
    }
    else{
        while($Node.Parent -ne $null){
            $Node = Get-View -Id $Node.Parent
            if($Node -is [VMware.Vim.Folder] -and $Node.Name -eq $targetParent){
                $foundType = $true
                break
            }
        }
    }

    Write-Verbose -Message "$(Get-Date) FoundType: $($foundType)" 
    Write-Verbose -Message "$(Get-Date) $($s = Get-PSCallStack;"Leaving {0}" -f $s[0].FunctionName)" 

    return $foundType
}