Public/WinREWiFi.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
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
<#
.SYNOPSIS
Connects to the selected WiFi Network SSID. Requires WinRE
 
.Description
Connects to the selected WiFi Network SSID. Requires WinRE
 
.PARAMETER SSID
WiFi Network SSID to connect to
 
.LINK
https://osdcloud.osdeploy.com
 
.NOTES
Author: Ondrej Sebela
GitHub: https://github.com/ztrhgf
#>

function Connect-WinREWiFi {
    [CmdletBinding()]
    param (
        [Parameter(Mandatory = $true)]
        [string] $SSID
    )

    $network = Get-WinREWiFi | Where-Object { $_.SSID -eq $SSID }

    $password = ""
    $notWPA2 = ""
    if ($network.Authentication -ne "Open") {
        $cred = Get-Credential -Message "Enter password for WIFI network '$SSID'" -UserName $SSID
        $password = $cred.GetNetworkCredential().password

        #TODO it can be WEP or enterprise ...but I don't know how Authentication value look like for them
        $notWPA2 = $network | Where-Object { $_.Authentication -ne "WPA2-Personal" }
    }

    # just for sure
    $null = Netsh WLAN delete profile "$SSID"

    # create new network profile
    $param = @{
        WLanName = $SSID
    }
    if ($password) { $param.Passwd = $password }
    if ($notWPA2) { $param.WPA = $true }
    Set-WinREWiFi @param

    # connect to network
    $result = Netsh WLAN connect name="$SSID"
    if ($result -ne "Connection request was completed successfully.") {
        throw "Connection to WIFI wasn't successful. Error was $result"
    }
}
<#
.SYNOPSIS
Returns WiFi Network SSID's. Requires WinRE
 
.Description
Returns WiFi Network SSID's. Requires WinRE
 
.PARAMETER SSID
Returns detailed information about the SSID
 
.LINK
https://osdcloud.osdeploy.com
 
.LINK
https://github.com/si-kotic/Manage-WirelessNetworks
 
.NOTES
Author: Ondrej Sebela
GitHub: https://github.com/ztrhgf
#>

function Get-WinREWiFi {
    [CmdletBinding()]
    param (
        [Parameter(ValueFromPipeline = $true)]
        $SSID
    )
    $response = netsh wlan show networks mode=bssid
    $wLANs = $response | Where-Object { $_ -match "^SSID" } | ForEach-Object {
        $report = "" | Select-Object SSID, Index, NetworkType, Authentication, Encryption, Signal
        $i = $response.IndexOf($_)
        $report.SSID = $_ -replace "^SSID\s\d+\s:\s", ""
        $report.Index = $i
        $report.NetworkType = $response[$i + 1].Split(":")[1].Trim()
        $report.Authentication = $response[$i + 2].Split(":")[1].Trim()
        $report.Encryption = $response[$i + 3].Split(":")[1].Trim()
        $report.Signal = $response[$i + 5].Split(":")[1].Trim()
        $report
    }
    if ($SSID) {
        $wLANs | Where-Object { $_.SSID -eq $SSID }
    } else {
        $wLANs
    }
}
<#
.SYNOPSIS
Creates a WiFi Network Profile. Requires WinRE
 
.Description
Creates a WiFi Network Profile. Requires WinRE
 
.PARAMETER Passwd
Password for the Network Profile
 
.PARAMETER WLanName
Name of the WiFi Network Profile
 
.PARAMETER WPA
Creates a WPA WiFi Network Profile
 
.LINK
https://osdcloud.osdeploy.com
 
.LINK
https://www.powershellgallery.com/packages/WifiTools/1.2
 
.NOTES
Author: Ondrej Sebela
GitHub: https://github.com/ztrhgf
#>

function Set-WinREWiFi() {
    [CmdletBinding()]
    param (
        [Parameter(Mandatory = $true, HelpMessage = "Please add Wireless network name")]
        [string]$WLanName,
        
        [string]$Passwd,
        
        [Parameter(Mandatory = $false, HelpMessage = "This switch will generate a WPA profile instead of WPA2")]
        [switch]$WPA = $false
    )

    if ($Passwd) {
        # escape XML special characters
        $Passwd = [System.Security.SecurityElement]::Escape($Passwd)
    }

    if ($WPA -eq $false) {
        $WpaState = "WPA2PSK"
        $EasState = "AES"
    } else {
        $WpaState = "WPAPSK"
        $EasState = "AES"
    }

    $XMLProfile = @"
<?xml version="1.0"?>
<WLANProfile xmlns="http://www.microsoft.com/networking/WLAN/profile/v1">
      <name>$WlanName</name>
      <SSIDConfig>
         <SSID>
              <name>$WLanName</name>
          </SSID>
     </SSIDConfig>
     <connectionType>ESS</connectionType>
     <connectionMode>auto</connectionMode>
     <MSM>
         <security>
             <authEncryption>
                 <authentication>$WpaState</authentication>
                 <encryption>$EasState</encryption>
                 <useOneX>false</useOneX>
             </authEncryption>
             <sharedKey>
                 <keyType>passPhrase</keyType>
                 <protected>false</protected>
                <keyMaterial>$Passwd</keyMaterial>
            </sharedKey>
        </security>
    </MSM>
</WLANProfile>
"@


    if ($Passwd -eq "") {
        $XMLProfile = @"
<?xml version="1.0"?>
<WLANProfile xmlns="http://www.microsoft.com/networking/WLAN/profile/v1">
    <name>$WLanName</name>
    <SSIDConfig>
        <SSID>
            <name>$WLanName</name>
        </SSID>
    </SSIDConfig>
    <connectionType>ESS</connectionType>
    <connectionMode>manual</connectionMode>
    <MSM>
        <security>
            <authEncryption>
                <authentication>open</authentication>
                <encryption>none</encryption>
                <useOneX>false</useOneX>
            </authEncryption>
        </security>
    </MSM>
    <MacRandomization xmlns="http://www.microsoft.com/networking/WLAN/profile/v3">
        <enableRandomization>false</enableRandomization>
    </MacRandomization>
</WLANProfile>
"@

    }

    $WLanName = $WLanName -replace "\s+"
    $WlanConfig = "$env:TEMP\$WLanName.xml"
    $XMLProfile | Set-Content $WlanConfig
    $result = Netsh WLAN add profile filename=$WlanConfig
    Remove-Item $WlanConfig -ErrorAction SilentlyContinue
    if ($result -notmatch "is added on interface") {
        throw "There was en error when setting up WIFI $WLanName connection profile. Error was $result"
    }
}
<#
.SYNOPSIS
Starts the WiFi Network Profile connection Wizard. Requires WinRE
 
.Description
Starts the WiFi Network Profile connection Wizard. Requires WinRE
 
.LINK
https://osdcloud.osdeploy.com
 
.NOTES
Author: Ondrej Sebela
GitHub: https://github.com/ztrhgf
 
Author: David Segura
GitHub: https://github.com/OSDeploy
#>

function Start-WinREWiFi {
    [CmdletBinding()]
    param ()
    #=======================================================================
    # Block
    #=======================================================================
    #Block-WinOS
    Block-PowerShellVersionLt5
    #=======================================================================
    # Header
    #=======================================================================
    Write-Host -ForegroundColor DarkGray "========================================================================="
    Write-Host -ForegroundColor Cyan "$((Get-Date).ToString('yyyy-MM-dd-HHmmss')) $($MyInvocation.MyCommand.Name) " -NoNewline
    Write-Host -ForegroundColor Green 'OK'
    #=======================================================================
    # Test Internet Connection
    #=======================================================================
    Write-Host -ForegroundColor Cyan "$((Get-Date).ToString('yyyy-MM-dd-HHmmss')) Test-WebConnection google.com " -NoNewline

    if (Test-WebConnection -Uri 'google.com') {
        Write-Host -ForegroundColor Green 'OK'
        Write-Host -ForegroundColor DarkGray "You are already connected to the Internet"
        Write-Host -ForegroundColor DarkGray "Start-WinREWiFi will not continue"
        $StartWinREWiFi = $false
    }
    else {
        Write-Host -ForegroundColor Red 'FAIL'
        $StartWinREWiFi = $true
    }
    #=======================================================================
    # Test WinRE
    #=======================================================================
    if ($StartWinREWiFi) {
        Write-Host -ForegroundColor Cyan "$((Get-Date).ToString('yyyy-MM-dd-HHmmss')) Testing required WinRE content " -NoNewline

        if (!(Test-Path "$ENV:SystemRoot\System32\dmcmnutils.dll")) {
            #Write-Warning "Missing required $ENV:SystemRoot\System32\dmcmnutils.dll"
            $StartWinREWiFi = $false
        }
        if (!(Test-Path "$ENV:SystemRoot\System32\mdmpostprocessevaluator.dll")) {
            #Write-Warning "Missing required $ENV:SystemRoot\System32\mdmpostprocessevaluator.dll"
            $StartWinREWiFi = $false
        }
        if (!(Test-Path "$ENV:SystemRoot\System32\mdmregistration.dll")) {
            #Write-Warning "Missing required $ENV:SystemRoot\System32\mdmregistration.dll"
            $StartWinREWiFi = $false
        }
        if (!(Test-Path "$ENV:SystemRoot\System32\raschap.dll")) {
            #Write-Warning "Missing required $ENV:SystemRoot\System32\raschap.dll"
            $StartWinREWiFi = $false
        }
        if (!(Test-Path "$ENV:SystemRoot\System32\raschapext.dll")) {
            #Write-Warning "Missing required $ENV:SystemRoot\System32\raschapext.dll"
            $StartWinREWiFi = $false
        }
        if (!(Test-Path "$ENV:SystemRoot\System32\rastls.dll")) {
            #Write-Warning "Missing required $ENV:SystemRoot\System32\rastls.dll"
            $StartWinREWiFi = $false
        }
        if (!(Test-Path "$ENV:SystemRoot\System32\rastlsext.dll")) {
            #Write-Warning "Missing required $ENV:SystemRoot\System32\rastlsext.dll"
            $StartWinREWiFi = $false
        }
        if ($StartWinREWiFi) {
            Write-Host -ForegroundColor Green 'OK'
        }
        else {
            Write-Host -ForegroundColor Red 'FAIL'
        }
    }
    #=======================================================================
    # WlanSvc
    #=======================================================================
    if ($StartWinREWiFi) {
        Write-Host -ForegroundColor Cyan "$((Get-Date).ToString('yyyy-MM-dd-HHmmss')) Starting WlanSvc Service" -NoNewline
        if (Get-Service -Name WlanSvc) {
            if ((Get-Service -Name WlanSvc).Status -ne 'Running') {
                Get-Service -Name WlanSvc | Start-Service
                Start-Sleep -Seconds 10
    
            }
        }
        Write-Host -ForegroundColor Green 'OK'
    }
    #=======================================================================
    # Test Wi-Fi Adapter
    #=======================================================================
    if ($StartWinREWiFi) {
        Write-Host -ForegroundColor Cyan "$((Get-Date).ToString('yyyy-MM-dd-HHmmss')) Testing Wi-Fi Network Adapter " -NoNewline
        $WirelessNetworkAdapter = Get-WmiObject -ClassName Win32_NetworkAdapter | Where-Object {$_.NetConnectionID -eq 'Wi-Fi'}
        #$WirelessNetworkAdapter = Get-SmbClientNetworkInterface | Where-Object {$_.FriendlyName -eq 'Wi-Fi'}
        if ($WirelessNetworkAdapter) {
            $StartWinREWiFi = $true
            Write-Host -ForegroundColor Green 'OK'
            Write-Host -ForegroundColor Gray " Name: $($WirelessNetworkAdapter.Name)"
            Write-Host -ForegroundColor Gray " Description: $($WirelessNetworkAdapter.Description)"
            #Write-Host -ForegroundColor Gray " Speed: $($WirelessNetworkAdapter.Speed)"
            Write-Host -ForegroundColor Gray " AdapterType: $($WirelessNetworkAdapter.AdapterType)"
            #Write-Host -ForegroundColor Gray " Installed: $($WirelessNetworkAdapter.Installed)"
            #Write-Host -ForegroundColor Gray " InterfaceIndex: $($WirelessNetworkAdapter.InterfaceIndex)"
            Write-Host -ForegroundColor Gray " MACAddress: $($WirelessNetworkAdapter.MACAddress)"
            #Write-Host -ForegroundColor Gray " NetEnabled: $($WirelessNetworkAdapter.NetEnabled)"
            #Write-Host -ForegroundColor Gray " PhysicalAdapter: $($WirelessNetworkAdapter.PhysicalAdapter)"
            Write-Host -ForegroundColor Gray " PNPDeviceID: $($WirelessNetworkAdapter.PNPDeviceID)"
        }
        else {
            $PnPEntity = Get-WmiObject -ClassName Win32_PnPEntity | Where-Object {$_.Status -eq 'Error'} |  Where-Object {$_.Name -match 'Net'}

            Write-Host -ForegroundColor Red 'FAIL'
            Write-Warning "Could not find an installed Wi-Fi Network Adapter"
            if ($PnPEntity) {
                Write-Warning "Drivers may need to be added to WinPE for the following hardware"
                foreach ($Item in $PnPEntity) {
                    Write-Warning "$($Item.Name): $($Item.DeviceID)"
                }
                Start-Sleep -Seconds 10
            }
            else {
                Write-Warning "Drivers may need to be added to WinPE"
            }
            $StartWinREWiFi = $false
        }
    }
    #=======================================================================
    # Test Wi-Fi Connection
    #=======================================================================
    if ($StartWinREWiFi) {
        Write-Host -ForegroundColor Cyan "$((Get-Date).ToString('yyyy-MM-dd-HHmmss')) Testing Wi-Fi Network Connection " -NoNewline
        if ($WirelessNetworkAdapter.NetEnabled -eq $true) {
            Write-Host -ForegroundColor Green ''
            Write-Warning "Wireless is already connected ... Disconnecting"
            (Get-WmiObject -ClassName Win32_NetworkAdapter | Where-Object {$_.NetConnectionID -eq 'Wi-Fi'}).disable() | Out-Null
            Start-Sleep -Seconds 5
            (Get-WmiObject -ClassName Win32_NetworkAdapter | Where-Object {$_.NetConnectionID -eq 'Wi-Fi'}).enable() | Out-Null
            Start-Sleep -Seconds 5
            $StartWinREWiFi = $true
        }
        else {
            Write-Host -ForegroundColor Green 'OK'
        }
    }
    #=======================================================================
    # Connect
    #=======================================================================
    if ($StartWinREWiFi) {
        Write-Host -ForegroundColor Cyan "$((Get-Date).ToString('yyyy-MM-dd-HHmmss')) Starting Wi-Fi Network Menu " -NoNewline
        Write-Host -ForegroundColor Green 'OK'
        Write-Host -ForegroundColor DarkGray "========================================================================="
        while (((Get-CimInstance -ClassName Win32_NetworkAdapter | Where-Object {$_.NetConnectionID -eq 'Wi-Fi'}).NetEnabled) -eq $false) {
            Start-Sleep -Seconds 3
            $SSIDList = Get-WinREWiFi
            if ($SSIDList) {
                #show list of available SSID
                $SSIDList | Sort-Object Signal -Descending | Select-Object Signal, Index, SSID, Authentication, Encryption, NetworkType | Format-Table
    
                $SSIDListIndex = $SSIDList.index
                $SSIDIndex = ""
                while ($SSIDIndex -notin $SSIDListIndex) {
                    $SSIDIndex = Read-Host "Select the Index of Wi-Fi Network to connect or CTRL+C to quit"
                }
    
                $SSID = $SSIDList | Where-Object { $_.index -eq $SSIDIndex } | Select-Object -exp SSID
    
                # connect to selected Wi-Fi
                Write-Host -ForegroundColor DarkGray "========================================================================="
                Write-Host -ForegroundColor Cyan "$((Get-Date).ToString('yyyy-MM-dd-HHmmss')) Establishing a connection to SSID $SSID"
                try {
                    Connect-WinREWiFi $SSID -ErrorAction Stop
                } catch {
                    Write-Warning $_
                    continue
                }
            } else {
                Write-Warning "No Wi-Fi network found. Move closer to AP or use ethernet cable instead."
            }

            Write-Host -ForegroundColor Cyan "$((Get-Date).ToString('yyyy-MM-dd-HHmmss')) Waiting for a connection to SSID $SSID"
            Start-Sleep -Seconds 15
        
            $i = 30
            while ((((Get-CimInstance -ClassName Win32_NetworkAdapter | Where-Object {$_.NetConnectionID -eq 'Wi-Fi'}).NetEnabled) -eq $false) -and $i -gt 0) {
                --$i
                Write-Host -ForegroundColor DarkGray "Waiting for Wi-Fi Connection ($i)"
                Start-Sleep -Seconds 1
            }

            # connection to network can take a while
            #$i = 30
            #while (!(Test-WebConnection -Uri 'github.com') -and $i -gt 0) { --$i; "Waiting for Internet connection ($i)" ; Start-Sleep -Seconds 1 }
        }
        Get-SmbClientNetworkInterface | Where-Object {$_.FriendlyName -eq 'Wi-Fi'} | Format-List
    }
    Start-Sleep -Seconds 5
}