PoshCode Archive  Check-in [0d5e172abf]

Many hyperlinks are disabled.
Use anonymous login to enable hyperlinks.

Overview
Comment:Found at https://github.com/gregzakh/alt-ps/blob/master/Get-MacAddress.ps1
Downloads: Tarball | ZIP archive | SQL archive
Timelines: family | ancestors | descendants | both | trunk
Files: files | file ages | folders
SHA3-256:0d5e172abf7e85e5c22ddb1f841cecccdedebefe005da9426b22f7002b3570c7
User & Date: terran 2018-06-10 14:16:16
Context
2018-06-10
14:16
This function is a wrapper for the Invoke-SSH cmdlet which is included in the Netcmdlets package (http://www.nsoftware.com/PowerShell/). I don’t care for its output or syntax complexity, so I made this to suit my needs. check-in: f29882008e user: unknown tags: trunk
14:16
Found at https://github.com/gregzakh/alt-ps/blob/master/Get-MacAddress.ps1 check-in: 0d5e172abf user: terran tags: trunk
14:16
A trace/logging system that wraps Write-Verbose, Write-Debug or Write-Warning to add timestamps and invocation source to the output, as well as allowing complicated messages to be calculated only when the output will actually be displayed. check-in: 432fd13941 user: Joel Bennett tags: trunk
Changes

Added Get-MacAddress.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
# encoding: ascii
# api: powershell
# title: Get-MacAddress
# description: Found at https://github.com/gregzakh/alt-ps/blob/master/Get-MacAddress.ps1
# version: 0.1
# type: function
# author: terran
# license: CC0
# function: Get-MacAddress
# x-poshcode-id: 6458
# x-archived: 2016-09-07T05:22:31
# x-published: 2016-07-27T13:30:00
#
#
function Get-MacAddress {
  <#
    .SYNOPSIS
        Gets MAC address.
    .NOTES
        Alternative ways to do same.
        
        Example 1:
        $asm = Add-Type -MemberDefinition @'
          [DllImport("rpcrt4.dll")]
          public static extern Int32 UuidCreateSequential(
              out Guid guid
          );
        '@ -Name Uuid -NameSpace MacAddress -PassThru
        $guid = New-Object Guid
        
        if (($res = $asm::UuidCreateSequential([ref]$guid)) -ne 0) {
          (New-Object ComponentModel.Win32Exception($res)).Message
          break
        }
        [Regex]::Replace(
          $guid.Guid.Split('-')[-1], '.{2}', '$0-'
        ).TrimEnd('-')
        
        Example 2:
        Get-WmiObject Win32_NetworkAdapter | Where-Object {
          $_.MacAddress
        } | ForEach-Object {
          New-Object PSObject -Property @{
            Description = $_.Description
            Service     = $_.ServiceName
            MACAddress  = $_.MACAddress
          }
        } | Select-Object Description, Service, MACAddress
        
        Example 3:
        Get-WmiObject Win32_NetworkAdapterConfiguration | Where-Object {
          $_.MacAddress
        } | ForEach-Object {
          New-Object PSObject -Property @{
            Description = $_.Description
            Id          = $_.SettingID
            MACAddress  = $_.MACAddress
          }
        } | Select-Object Description, Id, MACAddress
        
        Example 4:
        $mac, $nic = (getmac /fo csv | Where-Object {
          ![String]::IsNullOrEmpty($_) -and $_ -match '\w{2}\-'
        }).Split(',') | ForEach-Object {$_.Trim('"')}
        New-Object PSObject -Property @{
          Interface  = $nic.Substring(($$ = $nic.IndexOf('{')), $nic.Length - $$)
          MACAddress = $mac
        }
        
        Example 5:
        $key = 'HKLM:\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters\Interfaces\*'
        Get-ItemProperty $key | Where-Object {
          $_.DhcpIpAddress -and $_.DhcpIpAddress -ne '0.0.0.0'
        } | Select-Object DhcpIpAddress | ForEach-Object {
          New-Object PSObject -Property @{
            IPAddress  = $_.DhcpIpAddress
            MACAddress = ([Regex]'(\w{2}\-){5}\w{2}').Match((
              nbtstat -a $_.DhcpIpAddress
            )).Value
          }
        }
        
        Example 6:
        ([Regex]'(\w{2}\-){5}\w{2}').Match((
            ipconfig /all
        )).Value
        
        Example 7:
        ([Regex]'(\w{2}\s){6}').Match((
            route print
        )).Value.Trim().Replace([Char]32, '-')
  #>
  
  #there is no access denied error by path Global\.net clr networking
  #in CLR v4 for limited user, so...
  if (($clr = $PSVersionTable.CLRVersion.Major) -ge 4) {
    [Net.NetworkInformation.NetworkInterface]::GetAllNetworkInterfaces() |
    Where-Object {
      $_.OperationalStatus -eq [Net.NetworkInformation.OperationalStatus]::Up
    } | ForEach-Object {
      if (![String]::IsNullOrEmpty((
        $$ = $_.GetPhysicalAddress().ToString()
      ))) {
        New-Object PSObject -Property @{
          Id         = $_.Id
          MACAddress = [Regex]::Replace($$, '.{2}', '$0-').TrimEnd('-')
        }
      }
    } | Select-Object Description, Id, MACAddress | Format-List
  }
  elseif ($clr -eq 2) {
    @(
      [Runtime.InteropServices.CallingConvention],
      [Runtime.InteropServices.Marshal],
      [Reflection.BindingFlags],
      [Reflection.Emit.OpCodes]
    ) | ForEach-Object {
      $keys = ($ta = [PSObject].Assembly.GetType(
        'System.Management.Automation.TypeAccelerators'
      ))::Get.Keys
      $collect = @()
    }{
      if ($keys -notcontains $_.Name) {
        $ta::Add($_.Name, $_)
      }
      $collect += $_.Name
    }
    
    function Get-LastError {
      param(
        [Int32]$ErrorCode = [Marshal]::GetLastWin32Error()
      )
      
      [PSObject].Assembly.GetType(
        'Microsoft.PowerShell.Commands.Internal.Win32Native'
      ).GetMethod(
        'GetMessage', [BindingFlags]40
      ).Invoke(
        $null, @($ErrorCode)
      )
    }
    
    function private:Invoke-FreeLibrary {
      param(
        [Parameter(Mandatory=$true)]
        [IntPtr]$ModuleHandle
      )
      
      [void][Linq.Enumerable].Assembly.GetType(
        'Microsoft.Win32.UnsafeNativeMethods'
      ).GetMethod(
        'FreeLibrary', [BindingFlags]40
      ).Invoke($null, @($ModuleHandle))
    }
    
    function private:Get-ProcAddress {
      param(
        [Parameter(Mandatory=$true, Position=0)]
        [ValidateNotNullOrEmpty()]
        [String]$Module,
        
        [Parameter(Mandatory=$true, Position=1)]
        [ValidateNotNullOrEmpty()]
        [String]$Function
      )
      
      [Data.Rule].Assembly.GetType(
        'System.Data.Common.SafeNativeMethods'
      ).GetMethods(
        [BindingFlags]40
      ) | Where-Object {
        $_.Name -cmatch '\AGet(ProcA|ModuleH)'
      } | ForEach-Object {
        Set-Variable $_.Name $_
      }
      
      if (($ptr = $GetModuleHandle.Invoke(
        $null, @($Module)
      )) -eq [IntPtr]::Zero) {
        if (($mod = [Regex].Assembly.GetType(
          'Microsoft.Win32.SafeNativeMethods'
        ).GetMethod('LoadLibrary').Invoke(
          $null, @($Module)
        )) -eq [IntPtr]::Zero) {
          Write-Warning "$(Get-LastError)"
          break
        }
        $ptr = $GetModuleHandle.Invoke($null, @($Module))
      }
      
      $GetProcAddress.Invoke($null, @($ptr, $Function)), $mod
    }
    
    function private:Set-Delegate {
      param(
        [Parameter(Mandatory=$true, Position=0)]
        [ValidateScript({$_ -ne [IntPtr]::Zero})]
        [IntPtr]$ProcAddress,
        
        [Parameter(Mandatory=$true, Position=1)]
        [ValidateNotNullOrEmpty()]
        [String]$Delegate
      )
      
      $proto = Invoke-Expression $Delegate
      $method = $proto.GetMethod('Invoke')
      
      $returntype = $method.ReturnType
      $paramtypes = $method.GetParameters() |
                                    Select-Object -ExpandProperty ParameterType
      
      $holder = New-Object Reflection.Emit.DynamicMethod(
        'Invoke', $returntype, $paramtypes, $proto
      )
      $il = $holder.GetILGenerator()
      0..($paramtypes.Length - 1) | ForEach-Object {
        $il.Emit([OpCodes]::Ldarg, $_)
      }
      
      switch ([IntPtr]::Size) {
        4 { $il.Emit([OpCodes]::Ldc_I4, $ProcAddress.ToInt32()) }
        8 { $il.Emit([OpCodes]::Ldc_I8, $ProcAddress.ToInt64()) }
      }
      $il.EmitCalli(
        [OpCodes]::Calli, [CallingConvention]::StdCall, $returntype, $paramtypes
      )
      $il.Emit([OpCodes]::Ret)
      
      $holder.CreateDelegate($proto)
    }
    
    $ptr, $mod = Get-ProcAddress iphlpapi SendARP
    $SendARP = Set-Delegate $ptr `
                              '[Func[UInt32, UInt32, [Byte[]], [Byte[]], Int32]]'
    
    $key = 'HKLM:\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters\Interfaces\*'
    Get-ItemProperty $key | Where-Object {
      $_.DhcpIpAddress -and $_.DhcpIpAddress -ne '0.0.0.0'
    } | ForEach-Object {
      $inet_addr = [Regex].Assembly.GetType(
        'System.Net.UnsafeNclNativeMethods+OSSOCK'
      ).GetMethod('inet_addr', [BindingFlags]40)
    }{
      $adr = [BitConverter]::ToUInt32(
        [BitConverter]::GetBytes(
          $inet_addr.Invoke($null, @($_.DhcpIpAddress)
        )), 0
      )
      $mac = New-Object Byte[] 6
      $len = [BitConverter]::GetBytes($mac.Length)
      
      if (($ret = $SendARP.Invoke($adr, 0, $mac, $len)) -ne 0) {
        Write-Warning "$(Get-LastError $ret)"
        break
      }
      
      New-Object PSObject -Property @{
        Id         = $_.PSChildName
        MACAddress = ($mac | ForEach-Object {'{0:X2}' -f $_}) -join '-'
      }
    }
    
    if ($mod) { Invoke-FreeLibrary $mod }
    $collect | ForEach-Object { [void]$ta::Remove($_) }
  }
}