1 #!powershell
2 
3 # Copyright: (c) 2019, Thomas Moore (@tmmruk) <hi@tmmr.uk>
4 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
5 
6 #AnsibleRequires -CSharpUtil Ansible.Basic
7 
8 $spec = @{
9     options = @{
10         state = @{ type = "str"; choices = "enabled", "disabled", "default"; required = $true }
11         adapter_names = @{ type = "list"; elements = "str"; required = $false }
12     }
13     supports_check_mode = $true
14 }
15 
16 $module = [Ansible.Basic.AnsibleModule]::Create($args, $spec)
17 $module.Result.reboot_required = $false
18 
19 $state = $module.Params.state
20 $adapter_names = $module.Params.adapter_names
21 
22 switch ( $state )
23 {
24     'default'{ $netbiosoption = 0 }
25     enabled { $netbiosoption = 1 }
26     disabled { $netbiosoption = 2 }
27 }
28 
29 if(-not $adapter_names)
30 {
31     # Target all network adapters on the system
32     $get_params = @{
33         ClassName = 'Win32_NetworkAdapterConfiguration'
=()34         Filter = 'IPEnabled=true'
35         Property = @('MacAddress', 'TcpipNetbiosOptions')
36     }
37     $target_adapters_config = Get-CimInstance @get_params
38 }
39 else
40 {
41     $get_params = @{
42         Class = 'Win32_NetworkAdapter'
43         Filter = ($adapter_names | ForEach-Object -Process { "NetConnectionId='$_'" }) -join " OR "
44         KeyOnly = $true
45     }
46     $target_adapters_config = Get-CimInstance @get_params | Get-CimAssociatedInstance -ResultClass 'Win32_NetworkAdapterConfiguration'
47     if(($target_adapters_config | Measure-Object).Count -ne $adapter_names.Count)
48     {
49         $module.FailJson("Not all of the target adapter names could be found on the system. No configuration changes have been made. $adapter_names")
50     }
51 }
52 
53 foreach($adapter in $target_adapters_config)
54 {
55     if($adapter.TcpipNetbiosOptions -ne $netbiosoption)
56     {
57         if(-not $module.CheckMode)
58         {
59             $result = Invoke-CimMethod -InputObject $adapter -MethodName SetTcpipNetbios -Arguments @{TcpipNetbiosOptions=$netbiosoption}
60             switch ( $result.ReturnValue )
61             {
62                 0 { <# Success no reboot required #> }
63                 1 { $module.Result.reboot_required = $true }
64                 100 { $module.Warn("DHCP not enabled on adapter $($adapter.MacAddress). Unable to set default. Try using disabled or enabled options instead.") }
65                 default { $module.FailJson("An error occurred while setting TcpipNetbios options on adapter $($adapter.MacAddress). Return code $($result.ReturnValue).") }
66             }
67         }
68         $module.Result.changed = $true
69     }
70 }
71 
72 $module.ExitJson()
73