-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathInstall-PrepLapCode.ps1
More file actions
403 lines (342 loc) · 13.5 KB
/
Copy pathInstall-PrepLapCode.ps1
File metadata and controls
403 lines (342 loc) · 13.5 KB
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
<#
Only relevant to mazars (Install/Update mazars-prepare-laptop-code)
#>
#==========================================================================
#
# CONFIGURATION
#
$SOURCE_DIR = "\\mazars-gr.local\NETLOGON\IT-scripts\prepare-laptop"
$DEST_DIR = "C:\IT\bin"
$MAIN_PREPLAPTOP_SCRIPT = "$DEST_DIR\mazars-prepare-laptop-code.ps1"
$MAZARS_LAN = '10.30.0.0/16'
#
#==========================================================================
function Test-ShareLikelyUp {
<#
.SYNOPSIS
Quickly tests whether a UNC share host is LIKELY reachable over SMB.
.DESCRIPTION
Parses the host from a UNC share path, optionally verifies that at least one configured DNS server falls within an expected CIDR range, resolves the host to IPv4 and/or IPv6 addresses, and tests whether any resolved address accepts a TCP connection on port 445 within a short timeout.
This is a FAST reachability test, not a definitive share-access test. A positive result means the host likely has SMB available. It does not prove that the share exists or that the current user has access to it.
Supports hostnames, IPv4 UNC hosts, and Windows IPv6-literal UNC hosts.
.PARAMETER SharePath
UNC share path whose host will be tested.
.PARAMETER DnsCidrs
Optional CIDR ranges. When specified, at least one configured DNS server must fall within one of these ranges or the test returns a negative result.
.PARAMETER TcpTimeoutMs
For the connection test to TCP port 445 (SMB).
.OUTPUTS
A PSCustomObject with the test outcome and discovered details.
.EXAMPLE
Test-ShareLikelyUp -SharePath '\\server01\share'
.EXAMPLE
Test-ShareLikelyUp -SharePath '\\192.168.1.2\foo'
.EXAMPLE
Test-ShareLikelyUp -SharePath '\\server01.contoso.local\share' -DnsCidrs '10.30.0.0/16'
#>
[CmdletBinding()]
param(
[Parameter(Mandatory)]
[string]$SharePath,
[string[]]$DnsCidrs,
[int]$TcpTimeoutMs = 400
)
function Convert-IpAddressToBigInteger {
param([Parameter(Mandatory)][System.Net.IPAddress]$IpAddress)
$bytes = $IpAddress.GetAddressBytes()
[Array]::Reverse($bytes)
$unsignedBytes = New-Object byte[] ($bytes.Length + 1)
[Array]::Copy($bytes, 0, $unsignedBytes, 0, $bytes.Length)
[System.Numerics.BigInteger]::new($unsignedBytes)
}
function Test-IpInCidr {
param(
[Parameter(Mandatory)][string]$IpAddress,
[Parameter(Mandatory)][string]$Cidr
)
$parts = $Cidr -split '/'
if ($parts.Count -ne 2) {
throw "Invalid CIDR: $Cidr"
}
$networkIp = [System.Net.IPAddress]::Parse($parts[0])
$candidateIp = [System.Net.IPAddress]::Parse($IpAddress)
$prefixLength = [int]$parts[1]
if ($networkIp.AddressFamily -ne $candidateIp.AddressFamily) {
return $false
}
if ($candidateIp.AddressFamily -eq [System.Net.Sockets.AddressFamily]::InterNetwork) {
if ($prefixLength -lt 0 -or $prefixLength -gt 32) {
throw "Invalid IPv4 CIDR prefix length in $Cidr"
}
} elseif ($candidateIp.AddressFamily -eq [System.Net.Sockets.AddressFamily]::InterNetworkV6) {
if ($prefixLength -lt 0 -or $prefixLength -gt 128) {
throw "Invalid IPv6 CIDR prefix length in $Cidr"
}
} else {
throw "Unsupported address family in $Cidr"
}
$candidateValue = Convert-IpAddressToBigInteger -IpAddress $candidateIp
$networkValue = Convert-IpAddressToBigInteger -IpAddress $networkIp
$bitCount = if ($candidateIp.AddressFamily -eq [System.Net.Sockets.AddressFamily]::InterNetwork) { 32 } else { 128 }
if ($prefixLength -eq 0) {
return $true
}
$hostBits = $bitCount - $prefixLength
$candidatePrefix = $candidateValue -shr $hostBits
$networkPrefix = $networkValue -shr $hostBits
($candidatePrefix -eq $networkPrefix)
}
function Test-Tcp445Open {
param(
[Parameter(Mandatory)][string]$ComputerName,
[Parameter(Mandatory)][int]$TimeoutMs
)
$client = New-Object System.Net.Sockets.TcpClient
try {
$async = $client.BeginConnect($ComputerName, 445, $null, $null)
if (-not $async.AsyncWaitHandle.WaitOne($TimeoutMs, $false)) {
return $false
}
$null = $client.EndConnect($async)
return $true
} catch {
return $false
} finally {
$client.Close()
}
}
function ConvertFrom-Ipv6LiteralHost {
param([Parameter(Mandatory)][string]$HostName)
if ($HostName -notmatch '\.ipv6-literal\.net$') {
return $null
}
$base = $HostName -replace '\.ipv6-literal\.net$', ''
$ipv6 = $base.Replace('-', ':')
try {
$parsed = [System.Net.IPAddress]::Parse($ipv6)
if ($parsed.AddressFamily -eq [System.Net.Sockets.AddressFamily]::InterNetworkV6) {
return $parsed.IPAddressToString
}
return $null
} catch {
return $null
}
}
function Test-IsIpAddress {
param([Parameter(Mandatory)][string]$Text)
try {
$null = [System.Net.IPAddress]::Parse($Text)
return $true
} catch {
return $false
}
}
$result = [pscustomobject]@{
MatchingDnsServers = @()
ResolvedAddresses = @()
ReachableAddress = $null
LikelyUp = $false
FailureReason = $null
}
if ($SharePath -notmatch '^[\\]{2}([^\\]+)\\') {
$result.FailureReason = "SharePath is not a valid UNC path."
return $result
}
$targetHost = $Matches[1]
if ($DnsCidrs -and $DnsCidrs.Count -gt 0) {
$dnsServers = @()
try {
$dnsServers = @(Get-DnsClientServerAddress -ErrorAction Stop |
ForEach-Object { $_.ServerAddresses } |
Where-Object { $_ } |
Select-Object -Unique)
} catch {
$result.FailureReason = "Failed to read client DNS server configuration."
return $result
}
foreach ($dnsServer in $dnsServers) {
foreach ($cidr in $DnsCidrs) {
try {
if (Test-IpInCidr -IpAddress $dnsServer -Cidr $cidr) {
$result.MatchingDnsServers += $dnsServer
break
}
} catch {
}
}
}
$result.MatchingDnsServers = @($result.MatchingDnsServers | Select-Object -Unique)
if ($result.MatchingDnsServers.Count -eq 0) {
$result.FailureReason = "No configured DNS server matched the expected network list."
return $result
}
}
$ipv6LiteralAddress = ConvertFrom-Ipv6LiteralHost -HostName $targetHost
if ($ipv6LiteralAddress) {
$result.ResolvedAddresses = @($ipv6LiteralAddress)
} elseif (Test-IsIpAddress -Text $targetHost) {
$result.ResolvedAddresses = @(([System.Net.IPAddress]::Parse($targetHost)).IPAddressToString)
} else {
try {
$result.ResolvedAddresses = @([System.Net.Dns]::GetHostAddresses($targetHost) |
Where-Object {
$_.AddressFamily -eq [System.Net.Sockets.AddressFamily]::InterNetwork -or
$_.AddressFamily -eq [System.Net.Sockets.AddressFamily]::InterNetworkV6
} |
Select-Object -ExpandProperty IPAddressToString -Unique)
} catch {
$result.FailureReason = "DNS resolution failed."
return $result
}
if ($result.ResolvedAddresses.Count -eq 0) {
$result.FailureReason = "DNS resolution returned no IP addresses."
return $result
}
}
foreach ($address in $result.ResolvedAddresses) {
if (Test-Tcp445Open -ComputerName $address -TimeoutMs $TcpTimeoutMs) {
$result.ReachableAddress = $address
$result.LikelyUp = $true
return $result
}
}
$result.FailureReason = "No reachable TCP 445 endpoint was found."
return $result
}
function Write-HowToCopyCode {
Write-Host ""
Write-Host -for Cyan " %USERPROFILE%\enLogic\IT Support - Documents\scripts_and_SW_we_build\mazars\NETLOGON-IT-scripts-prepare-laptop\"
Write-Host -for DarkCyan " (YOUR PC)"
Write-Host -for DarkCyan " |"
Write-Host -for DarkCyan " _|_"
Write-Host -for DarkCyan " \ /"
Write-Host -for DarkCyan " V"
Write-Host -for DarkCyan " (Forvis Mazars LAPTOP)"
Write-Host -for Cyan " $DEST_DIR"
}
function Install-NuGetNonInteractively {
try {
[Net.ServicePointManager]::SecurityProtocol =
[Net.ServicePointManager]::SecurityProtocol -bor
[Net.SecurityProtocolType]::Tls12
Get-PackageProvider `
-Name NuGet `
-ForceBootstrap `
-ErrorAction Stop |
Out-Null
Write-Host 'NuGet provider is available.' -ForegroundColor Green
}
catch {
Write-Host 'Failed to install/load the NuGet provider.' -ForegroundColor Red
Write-Host $_.Exception.Message -ForegroundColor Red
throw
}
}
function Set-PSGalleryTrusted {
$repo = 'PSGallery'
try {
[Net.ServicePointManager]::SecurityProtocol =
[Net.ServicePointManager]::SecurityProtocol -bor
[Net.SecurityProtocolType]::Tls12
try {
$repository = Get-PSRepository `
-Name $repo `
-ErrorAction Stop
}
catch {
Register-PSRepository `
-Default `
-ErrorAction Stop
$repository = Get-PSRepository `
-Name $repo `
-ErrorAction Stop
}
if ($repository.InstallationPolicy -ne 'Trusted') {
Set-PSRepository `
-Name $repo `
-InstallationPolicy Trusted `
-ErrorAction Stop
Write-Host 'PSGallery has been set to Trusted.' -ForegroundColor Green
}
else {
Write-Host 'PSGallery is already Trusted.' -ForegroundColor Green
}
}
catch {
Write-Host 'Failed to configure PSGallery.' -ForegroundColor Red
Write-Host $_.Exception.Message -ForegroundColor Red
throw
}
}
function Install-PowerShellModuleNonInteractively {
[CmdletBinding()]
param (
[Parameter(Mandatory = $true)]
[ValidateNotNullOrEmpty()]
[string]$ModuleName
)
try {
[Net.ServicePointManager]::SecurityProtocol =
[Net.ServicePointManager]::SecurityProtocol -bor
[Net.SecurityProtocolType]::Tls12
Install-Module `
-Name $ModuleName `
-Repository PSGallery `
-Force `
-Confirm:$false `
-ErrorAction Stop
Write-Host "PowerShell module '$ModuleName' installed successfully." -ForegroundColor Green
}
catch {
Write-Host "Failed to install PowerShell module '$ModuleName'." -ForegroundColor Red
Write-Host $_.Exception.Message -ForegroundColor Red
throw
}
}
mkdir -force $DEST_DIR > $null
Install-NuGetNonInteractively
Set-PSGalleryTrusted
Install-PowerShellModuleNonInteractively -ModuleName PSWindowsUpdate
$copiedFilesFromDomain = $false
$r = Test-ShareLikelyUp -SharePath $SOURCE_DIR -DnsCidrs $MAZARS_LAN
if ($r.LikelyUp) {
if (Test-Path $SOURCE_DIR) {
Write-Host "Copying files from NETLOGON share of the domain:"
Write-Host " $SOURCE_DIR"
copy "$SOURCE_DIR\*.*" $DEST_DIR\
$copiedFilesFromDomain = $true
}
}
if (-not $copiedFilesFromDomain) {
if (Test-Path $MAIN_PREPLAPTOP_SCRIPT) {
Write-Host ""
$lastWriteTime = (Get-Item $MAIN_PREPLAPTOP_SCRIPT).LastWriteTime
$lastWriteTimeStr = Get-Date $lastWriteTime -format 'yyyy-MMM-dd'
if ($lastWriteTime -ge (Get-Date).AddDays(-15)) {
Write-Host -for DarkGray "Can't update existing code because we can't access " -NoNewLine
Write-Host -for DarkGray "\\mazars-gr.local\NETLOGON\IT-scripts\prepare-laptop"
Write-Host -for White "But don't bother" -NoNewLine
Write-Host -for DarkGray " -- your code is fresh ($lastWriteTimeStr)."
} else {
Write-Host -for White "Can't update existing code because we can't access " -NoNewLine
Write-Host -for Cyan "\\mazars-gr.local\NETLOGON\IT-scripts\prepare-laptop"
Write-Host ""
Write-Host -for White "Your code was last udpated at $lastWriteTimeStr " -NoNewLine
Write-Host -for Yellow "If you want to update, " -NoNewLine
Write-Host -for White "manually copy these files:"
Write-HowToCopyCode
}
} else {
Write-Host ""
Write-Host -for Red " _________________________________________________________________"
Write-Host -for Red " ERROR "
Write-Host -for Red ""
Write-Host -for Red " Can't access \\mazars-gr.local\NETLOGON\IT-scripts\prepare-laptop"
Write-Host -for Red " _________________________________________________________________"
Write-Host ""
Write-Host -for Yellow "Please manually copy these files:"
explorer.exe "$DEST_DIR"
Write-HowToCopyCode
}
}
Write-Host ""