DSCResources/cVMSwitch/cVMSwitch.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
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
#region localizeddata
if (Test-Path "${PSScriptRoot}\${PSUICulture}")
{
    Import-LocalizedData -BindingVariable localizedData -filename cVMSwitch.psd1 `
                         -BaseDirectory "${PSScriptRoot}\${PSUICulture}"
} 
else
{
    #fallback to en-US
    Import-LocalizedData -BindingVariable localizedData -filename cVMSwitch.psd1 `
                         -BaseDirectory "${PSScriptRoot}\en-US"
}
#endregion

function Get-TargetResource
{
    [CmdletBinding()]
    [OutputType([System.Collections.Hashtable])]
    param
    (
        [parameter(Mandatory)]
        [String]$Name,

        [parameter(Mandatory)]
        [ValidateSet("External","Internal","Private")]
        [String]$Type
    )

    if(!(Get-Module -ListAvailable -Name Hyper-V))
    {
        Throw $localizedData.HyperVModuleNotFound
    }
        
    $configuration = @{
        Name = $Name
        Type = $Type
    }

    $switch = Get-VMSwitch -Name $Name -SwitchType $Type -ErrorAction SilentlyContinue
    if ($switch)
    {
        Write-Verbose -Message $localizedData.FoundSwitch
        if ($switch.SwitchType -eq 'External')
        {
            Write-Verbose -Message $localizedData.FoundExternalSwitch

            #SET specific properties for External switch type
            if ($switch.EmbeddedTeamingEnabled)
            {
                Write-Verbose -Message $localizedData.FoundSetTeam
                $switchTeam = Get-VMSwitchTeam -Name $Name

                $netAdapterName = $(
                    $switchTeam.NetAdapterInterfaceDescription | 
                        Foreach-Object { 
                            (Get-NetAdapter -InterfaceDescription $_).Name
                        }
                )               
                $configuration.Add('TeamingMode',$switchTeam.TeamingMode)
                $configuration.Add('LoadBalancingAlgorithm',$switchTeam.LoadBalancingAlgorithm)
            }
            else
            {
                $netAdapterName = $( 
                    if($switch.NetAdapterInterfaceDescription)
                    {
                        (Get-NetAdapter -InterfaceDescription $switch.NetAdapterInterfaceDescription).Name
                    }
                )
            }
        }
        else
        {
            Write-Verbose -Message ($localizedData.FoundIntORPvtSwitch -f $switch.SwitchType)
        }
        
        $configuration.Add('NetAdapterName', $netAdapterName)
        $configuration.Add('NetAdapterInterfaceDescription',$switch.NetAdapterInterfaceDescriptions)
        $configuration.Add('EmbeddedTeamingEnabled',$switch.EmbeddedTeamingEnabled)
        $configuration.Add('AllowManagementOS',$switch.AllowManagementOS)
        $configuration.Add('Id',$switch.Id)
        $configuration.Add('EnableIoV',$switch.IovEnabled)
        $configuration.Add('EnablePacketDirect',$switch.PacketDirectEnabled)
        $configuration.Add('MinimumBandwidthMode',$switch.BandwidthReservationMode)
        $configuration.Add('Ensure','Present')
    }
    else
    {
        Write-Verbose -Message $localizedData.NoSwitchFound
        $configuration.Add('Ensure','Absent')
    }

    return $configuration
}

function Set-TargetResource
{
     [CmdletBinding()]
     param
     (
         [parameter(Mandatory)]
         [String] $Name,

         [parameter(Mandatory)]
         [ValidateSet('External','Internal','Private')]
         [String] $Type,

        [Parameter()]
        [ValidateNotNullOrEmpty()]
        [String[]] $NetAdapterName,

        [Parameter()]
        [Boolean] $AllowManagementOS,

        [Parameter()]
        [Boolean] $EnableIov,

        [Parameter()]
        [ValidateSet('None', 'Default', 'Weight', 'Absolute')]
        [String] $MinimumBandwidthMode='Absolute',
        
        [parameter()]
        [ValidateSet('SwitchIndependent')]
        [String] $TeamingMode,

        [parameter()]
        [ValidateSet('Dynamic','HyperVPort')]
        [String] $LoadBalancingAlgorithm,

        [Parameter()]
        [Boolean]$EnablePacketDirect,

        [ValidateSet("Present","Absent")]
        [String] $Ensure = "Present"
    )
    
    # Check if Hyper-V module is present for Hyper-V cmdlets
    if(!(Get-Module -ListAvailable -Name Hyper-V))
    {
        Throw $localizedData.HyperVModuleNotFound
    }

    if ((($Type -eq 'Internal') -or ($Type -eq 'Private')) -and $AllowManagementOS)
    {
        throw $localizedData.InternalPrivateWithAllowManagementOS
    }

    if ($Type -eq 'External' -and !($NetAdapterName))
    {
        throw $localizedData.NetAdapterNameForExternal
    }

    if ($Type -ne 'External' -and $NetAdapterName)
    {
        throw $localizedData.NoNetAdapterInternalPrivate
    }

    if (($TeamingMode -or $LoadBalancingAlgorithm) -and ($Type -ne 'External'))
    {
        throw $localizedData.NoSETForInternalPrivate
    }

    if ($EnableIov -and $EnablePacketDirect)
    {
        throw $localizedData.IOVPDTogether
    }

    if ($MinimumBandwidthMode -and ($EnableIov -and ($NetAdapterName.Count -gt 1)))
    {
        throw $localizedData.IOVMBwithSET
    }

    if ($MinimumBandwidthMode -and ($EnablePacketDirect -and ($NetAdapterName.Count -gt 1)))
    {
        throw $localizedData.PDMBwithSET
    }

    if($Ensure -eq 'Present')
    {
        $switch = (Get-VMSwitch -Name $Name -SwitchType $Type -ErrorAction SilentlyContinue)

        # If switch is present and it is external type, that means it doesn't have right properties (TEST code ensures that)
        if($switch)
        {
            Write-Verbose -Message $localizedData.FoundSwitch
            if ($switch.SwitchType -eq 'External')
            {
                Write-Verbose -Message $localizedData.FoundExternalSwitch
                
                #Check if there are multiple network adapters specified; it should be a SET Team
                if ($NetAdapterName.Count -gt 1)
                {
                    #We need a SET Team
                    Write-Verbose -Message $localizedData.NeedASET
                    if (-not $switch.EmbeddedTeamingEnabled)
                    {
                        #We dont have a SET team; delete and re-create the team
                        Write-Verbose -Message $localizedData.ReCreateSET

                        $switch | Remove-VMSwitch -Force
                        $arguments = @{
                            Name = $Name
                            NetAdapterName = $NetAdapterName
                            MinimumBandwidthMode = $MinimumBandwidthMode
                        }
                        
                        if ($PSBoundParameters.ContainsKey('AllowManagementOS'))
                        {
                            $arguments['AllowManagementOS']=$AllowManagementOS
                        }
                        
                        if ($PSBoundParameters.ContainsKey('TeamingMode'))
                        {
                            $arguments['TeamingMode']=$TeamingMode
                        }
                        
                        if ($PSBoundParameters.ContainsKey('LoadBalancingAlgorithm'))
                        {
                            $arguments['LoadBalancingAlgorithm']=$LoadBalancingAlgorithm
                        }
                        
                        if ($PSBoundParameters.ContainsKey("EnableIov"))
                        {
                            $arguments['EnableIov']=$EnableIov
                        }
                        
                        if ($PSBoundParameters.ContainsKey("EnablePacketDirect"))
                        {
                            $arguments['EnablePacketDirect']=$EnablePacketDirect
                        }
                        
                        Write-Verbose -Message $localizedData.CreateSwitch
                        $null = New-VMSwitch @arguments
                    }
                    else
                    {
                        #We have a SET Team; check network adapters and other properties
                        Write-Verbose -Message $localizedData.SETFoundCheckNetAdapter

                        $switchTeam = Get-VMSwitchTeam -VMSwitch $switch
                        $existngNetAdapters = $switchTeam.NetAdapterInterfaceDescription | 
                                ForEach-Object {
                                    (Get-NetAdapter -InterfaceDescription $_).Name
                                }
                        $switchTeamMembers = Compare-Object -ReferenceObject $NetAdapterName -DifferenceObject $existngNetAdapters
                    
                        $setTeamArguments = @{
                            VMSwitch = $switch
                        }

                        if ($null -ne $switchTeamMembers)
                        {
                            #We have a difference in the compared objects
                            Write-Verbose -Message $localizedData.SETMembersDontMatch

                            $setTeamArguments['NetAdapterName'] = $NetAdapterName
                            $updateTeam = $true
                        }

                        #check other propeties of the SET Team as well
                        if ($PSBoundParameters.ContainsKey('TeamingMode'))
                        {
                            if ($switchTeam.TeamingMode -ne $TeamingMode)
                            {
                                $setTeamArguments['TeamingMode']=$TeamingMode
                                $updateTeam = $true
                            }
                        }

                        if ($PSBoundParameters.ContainsKey('LoadBalancingAlgorithm'))
                        {
                            if ($switchTeam.LoadBalancingAlgorithm -ne $LoadBalancingAlgorithm)
                            {
                                $setTeamArguments['LoadBalancingAlgorithm']=$LoadBalancingAlgorithm
                                $updateTeam = $true
                            }
                        }

                        if ($updateTeam)
                        {
                            Write-Verbose -Message $localizedData.UpdateSETTeam
                            $null = Set-VMSwitchTeam @setTeamArguments
                        }

                        #Finally, check if if we need set AllowManagementOS
                        if($PSBoundParameters.ContainsKey("AllowManagementOS"))
                        {
                            Write-Verbose -Message "Checking if Switch $Name has AllowManagementOS set correctly..."
                            if(($switch.AllowManagementOS -ne $AllowManagementOS))
                            {
                                Write-Verbose -Message $localizedData.UpdateSwitch
                                $null = Set-VMSwitch -VMSwitch $switch -AllowManagementOS $AllowManagementOS
                            }
                        }
                    } 
                }
                else
                {
                    #We don't need a SET Team
                    if ($switch.EmbeddedTeamingEnabled)
                    {
                        #We have SET team; need to delete and re-create a normal switch
                        Write-Verbose -Message $localizedData.NeedANormalSwitch
                        Write-Verbose -Message $localizedData.RemovingSwitch
                        $switch | Remove-VMSwitch -Force

                        $switchArguments = @{
                            Name = $Name
                            NetAdapterName = $NetAdapterName
                            MinimumBandwidthMode = $MinimumBandwidthMode
                        }

                        if ($PSBoundParameters.ContainsKey('AllowManagementOS'))
                        {
                            $switchArguments['AllowManagementOS']=$AllowManagementOS
                        }
                    
                        if ($PSBoundParameters.ContainsKey("EnableIov"))
                        {
                            $switchArguments['EnableIov']=$EnableIov
                        }
                        if ($PSBoundParameters.ContainsKey("EnablePacketDirect"))
                        {
                            $switchArguments['EnablePacketDirect']=$EnablePacketDirect
                        }

                        Write-Verbose -Message $localizedData.CreateSwitch
                        $null = New-VMSwitch @switchArguments
                    }
                    else
                    {
                        #We have a normal switch; Check other properties
                        $switchUpdateArguments = @{
                            VMSwitch = $switch                            
                        }

                        if((Get-NetAdapter -Name $NetAdapterName).InterfaceDescription -ne $switch.NetAdapterInterfaceDescription)
                        {
                            #Network Adapter is not matching; we can set this without deleting the switch
                            $switchUpdateArguments['NetAdapterName'] = $NetAdapterName
                            $updateSwitch = $true
                        }
                    
                        if($PSBoundParameters.ContainsKey("AllowManagementOS"))
                        {
                            Write-Verbose -Message "Checking if Switch $Name has AllowManagementOS set correctly..."
                            if(($switch.AllowManagementOS -ne $AllowManagementOS))
                            {
                                $switchUpdateArguments['AllowManagementOS'] = $AllowManagementOS
                                $updateSwitch = $true
                            }
                        }
                    
                        if ($updateSwitch)
                        {
                            Write-Verbose -Message $localizedData.UpdateSwitch
                            $null = Set-VMSwitch @switchUpdateArguments
                        }
                    }
                }
            }
            else
            {
                #We have an internal or private switch; we cannot update any properties
                Write-Verbose -Message $localizedData.WeShouldNeverReachHere
            }
        }
        else
        {
            # If the switch is not present, create one
            $parameters = @{}
            $parameters["Name"] = $Name
            if($NetAdapterName)
            {
                $parameters["NetAdapterName"] = $NetAdapterName
                $parameters["MinimumBandwidthMode"] = $MinimumBandwidthMode
                if($PSBoundParameters.ContainsKey("AllowManagementOS"))
                {
                    $parameters["AllowManagementOS"] = $AllowManagementOS
                }
            }
            else
            { 
                $parameters["SwitchType"] = $Type
            }
            
            Write-Verbose -Message $localizedData.CreateSwitch
            $null = New-VMSwitch @parameters
        }
    }
    # Ensure is set to "Absent", remove the switch
    else
    {
        Write-Verbose -Message $localizedData.RemovingSwitch
        Get-VMSwitch $Name -ErrorAction SilentlyContinue | Remove-VMSwitch -Force
    }
}

function Test-TargetResource
{
    [CmdletBinding()]
    [OutputType([System.Boolean])]
    param
    (
        [parameter(Mandatory)]
        [String] $Name,

        [parameter(Mandatory)]
        [ValidateSet('External','Internal','Private')]
        [String] $Type,

        [Parameter()]
        [ValidateNotNullOrEmpty()]
        [String[]] $NetAdapterName,

        [Parameter()]
        [Boolean] $AllowManagementOS,

        [Parameter()]
        [Boolean] $EnableIov,

        [Parameter()]
        [ValidateSet('None', 'Default', 'Weight', 'Absolute')]
        [String] $MinimumBandwidthMode='Absolute',
        
        [parameter()]
        [ValidateSet('SwitchIndependent')]
        [String] $TeamingMode,

        [parameter()]
        [ValidateSet('Dynamic','HyperVPort')]
        [String] $LoadBalancingAlgorithm,

        [Parameter()]
        [Boolean]$EnablePacketDirect,

        [ValidateSet("Present","Absent")]
        [String] $Ensure = "Present"
    )

    # Check if Hyper-V module is present for Hyper-V cmdlets
    if(!(Get-Module -ListAvailable -Name Hyper-V))
    {
        Throw $localizedData.HyperVModuleNotFound
    }

    if ((($Type -eq 'Internal') -or ($Type -eq 'Private')) -and $AllowManagementOS)
    {
        throw $localizedData.InternalPrivateWithAllowManagementOS
    }

    if ($Type -eq 'External' -and !($NetAdapterName))
    {
        throw $localizedData.NetAdapterNameForExternal
    }

    if ($Type -ne 'External' -and $NetAdapterName)
    {
        throw $localizedData.NoNetAdapterInternalPrivate
    }

    if (($TeamingMode -or $LoadBalancingAlgorithm) -and ($Type -ne 'External'))
    {
        throw $localizedData.NoSETForInternalPrivate
    }

    if ($EnableIov -and $EnablePacketDirect)
    {
        throw $localizedData.IOVPDTogether
    }

    if ($MinimumBandwidthMode -and ($EnableIov -and ($NetAdapterName.Count -gt 1)))
    {
        throw $localizedData.IOVMBwithSET
    }

    if ($MinimumBandwidthMode -and ($EnablePacketDirect -and ($NetAdapterName.Count -gt 1)))
    {
        throw $localizedData.PDMBwithSET
    }

    try
    {
        $switch = Get-VMSwitch -Name $Name -SwitchType $Type -ErrorAction Stop

        if($switch)
        {
            Write-Verbose -Message $localizedData.FoundSwitch
            if ($Ensure -eq 'Present')
            {
                if ($NetAdapterName.Count -gt 1)
                {
                    Write-Verbose -Message $localizedData.NeedASET
                    #We need a SET team
                    if (-not $switch.EmbeddedTeamingEnabled)
                    {
                        Write-Verbose -Message $localizedData.ReCreateSET
                        return $false
                    }
                    else
                    {
                        #We have a SET team; need to compare the properties
                        $switchTeam = Get-VMSwitchTeam -Name $Name

                        if ($Type -eq 'External')
                        {
                            #Compare network adapters in the SET
                            Write-Verbose -Message $localizedData.SETFoundCheckNetAdapter
                            $existngNetAdapters = $switchTeam.NetAdapterInterfaceDescription | 
                                ForEach-Object { 
                                    (Get-NetAdapter -InterfaceDescription $_).Name 
                                }
                            $switchTeamMembers = Compare-Object -ReferenceObject $NetAdapterName `
                                                 -DifferenceObject $existngNetAdapters

                            if ($null -ne $switchTeamMembers)
                            {
                                #We have a difference in the compared objects
                                Write-Verbose -Message $localizedData.SETMembersDontMatch
                                return $false
                            }
                        }

                        if ($switchTeam.LoadBalancingAlgorithm -ne $LoadBalancingAlgorithm)
                        {
                            Write-Verbose -Message $localizedData.LBDifferent
                            return $false
                        }

                        if ($switchTeam.TeamingMode -ne $TeamingMode)
                        {
                            Write-Verbose -Message $localizedData.TeamingDifferent
                            return $false
                        }
                    }
                }
                else
                {
                    #We need a normal VM switch
                    if ($switch.EmbeddedTeamingEnabled)
                    {
                        Write-Verbose -Message $localizedData.NeedANormalSwitch
                        return $false
                    }

                    if ($Type -eq 'External')
                    {
                        if((Get-NetAdapter -Name $NetAdapterName -ErrorAction SilentlyContinue).InterfaceDescription -ne $switch.NetAdapterInterfaceDescription)
                        {
                            Write-Verbose -Message $localizedData.NetAdapterDifferent
                            return $false
                        }
                    }
                }

                #Check for common properties
                if($PSBoundParameters.ContainsKey("AllowManagementOS") -and $Type -eq 'External')
                {
                    if(($switch.AllowManagementOS -ne $AllowManagementOS))
                    {
                        Write-Verbose -Message $localizedData.AllowMgmtOSDifferent
                        return $false
                    }
                }

                if ($EnablePacketDirect)
                {
                    if (-not $switch.EnablePacketDirect) {
                        Write-Warning -Message $localizedData.EPDCannotChange
                    }                    
                }

                if ($EnableIov)
                {
                    if (-not $switch.EnableIov) {
                        Write-Warning -Message $localizedData.IOVCannotChange
                    } 
                }

                if ($MinimumBandwidthMode -ne $switch.BandwidthReservationMode)
                {
                    Write-Warning -Message $localizedData.MBCannotChange
                }
                
                #If we have reached this far, the switch exists with necessary configuration
                Write-Verbose -Message $localizedData.SwitchExistsNoAction
                return $true
            }
            else
            {
                Write-Verbose -Message $localizedData.SwitchExistsItShouldnot
                return $false       
            }
        }
        else
        {
            if ($Ensure -eq 'Present')
            {
                Write-Verbose -Message $localizedData.SwitchShouldExist
                return $false
            }
            else
            {
                Write-Verbose -Message $localizedData.SwitchDoesNotExistNoAction
                return $true
            }
        }
    }

    # If no switch was present
    catch [System.Management.Automation.ActionPreferenceStopException]
    {
        Write-Verbose -Message $localizedData.NoSwitchFound
        return ($Ensure -eq 'Absent')
    }
}

Export-ModuleMember -Function *-TargetResource