-
-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathdbatools.library.psm1
More file actions
331 lines (293 loc) · 12.8 KB
/
dbatools.library.psm1
File metadata and controls
331 lines (293 loc) · 12.8 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
param(
# Automatically skip loading assemblies that are already loaded (useful when SqlServer module is already imported)
[Alias('SkipLoadedAssemblies', 'AllowSharedAssemblies')]
[switch]$AvoidConflicts
)
function Get-DbatoolsLibraryPath {
[CmdletBinding()]
param()
if ($PSVersionTable.PSEdition -eq "Core") {
Join-Path -Path $PSScriptRoot -ChildPath core
} else {
Join-Path -Path $PSScriptRoot -ChildPath desktop
}
}
$script:libraryroot = Get-DbatoolsLibraryPath
if ($PSVersionTable.PSEdition -ne "Core") {
if (-not ("Redirector" -as [type])) {
$source = @"
using System;
using System.IO;
using System.Reflection;
public class Redirector
{
private static string _libPath;
public Redirector(string libPath)
{
_libPath = libPath;
this.EventHandler = new ResolveEventHandler(AssemblyResolve);
}
public readonly ResolveEventHandler EventHandler;
protected static Assembly AssemblyResolve(object sender, ResolveEventArgs e)
{
var requestedName = new AssemblyName(e.Name);
var assemblyName = requestedName.Name;
// First, check if any version of this assembly is already loaded
// This handles version mismatches (e.g., SMO requesting SqlClient 5.0.0.0 when 6.0.2 is loaded)
foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies())
{
try
{
if (assembly.GetName().Name == assemblyName)
{
return assembly;
}
}
catch
{
// Some assemblies may throw when accessing GetName()
}
}
// Try to load from our lib folder if the file exists
string dllPath = Path.Combine(_libPath, assemblyName + ".dll");
if (File.Exists(dllPath))
{
try
{
return Assembly.LoadFrom(dllPath);
}
catch
{
// Failed to load, return null to let default resolution continue
}
}
return null;
}
}
"@
$null = Add-Type -TypeDefinition $source
}
try {
$libPath = [System.IO.Path]::Combine($script:libraryroot, "lib")
$redirector = New-Object Redirector($libPath)
[System.AppDomain]::CurrentDomain.add_AssemblyResolve($redirector.EventHandler)
} catch {
Write-Verbose "Could not register Redirector: $_"
}
} else {
# PowerShell Core: Use AssemblyLoadContext.Resolving event for version redirection
# This handles version mismatches when SqlServer module loads different versions of assemblies
# IMPORTANT: Must be implemented in C# because the resolver runs on .NET threads without PowerShell runspaces
$dir = [System.IO.Path]::Combine($script:libraryroot, "lib")
$dir = ("$dir" + [System.IO.Path]::DirectorySeparatorChar).Replace('\', '\\')
if (-not ("CoreRedirector" -as [type])) {
$coreSource = @"
using System;
using System.IO;
using System.Reflection;
using System.Runtime.Loader;
public class CoreRedirector
{
private static string _libPath;
private static bool _registered = false;
public static void Register(string libPath)
{
if (_registered) return;
_libPath = libPath;
AssemblyLoadContext.Default.Resolving += OnResolving;
_registered = true;
}
private static Assembly OnResolving(AssemblyLoadContext context, AssemblyName assemblyName)
{
string name = assemblyName.Name;
// First, check if any version of this assembly is already loaded
// This handles version mismatches (e.g., dbatools.dll requesting ConnectionInfo 17.100.0.0 when 17.200.0.0 is loaded)
foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies())
{
try
{
if (assembly.GetName().Name == name)
{
return assembly;
}
}
catch
{
// Some assemblies may throw when accessing GetName()
}
}
// Try to load from our lib folder if the file exists
string dllPath = _libPath + name + ".dll";
if (File.Exists(dllPath))
{
try
{
return AssemblyLoadContext.Default.LoadFromAssemblyPath(dllPath);
}
catch
{
// Failed to load, return null to let default resolution continue
}
}
return null;
}
}
"@
try {
$null = Add-Type -TypeDefinition $coreSource -ReferencedAssemblies 'System.Runtime.Loader'
} catch {
Write-Verbose "Could not compile CoreRedirector: $_"
}
}
try {
[CoreRedirector]::Register($dir)
} catch {
Write-Verbose "Could not register CoreRedirector: $_"
}
}
# REMOVED win-sqlclient logic - SqlClient is now directly in lib
$sqlclient = [System.IO.Path]::Combine($script:libraryroot, "lib", "Microsoft.Data.SqlClient.dll")
# Get loaded assemblies once for reuse (used for AvoidConflicts checks and later assembly loading)
$script:loadedAssemblies = [System.AppDomain]::CurrentDomain.GetAssemblies()
# Check for incompatible System.ClientModel or SqlClient versions
# Azure.Core 1.44+ requires System.ClientModel 1.1+ with IPersistableModel.Write() method
# SqlServer module's SqlClient 5.x includes older System.ClientModel that's incompatible
$script:hasIncompatibleClientModel = $false
if ($AvoidConflicts) {
# Check if System.ClientModel is already loaded with incompatible version
$existingClientModel = $script:loadedAssemblies | Where-Object { $_.GetName().Name -eq 'System.ClientModel' }
if ($existingClientModel) {
$clientModelVersion = $existingClientModel.GetName().Version
# System.ClientModel 1.1.0+ has the required IPersistableModel interface changes
if ($clientModelVersion -lt [Version]'1.1.0') {
$script:hasIncompatibleClientModel = $true
Write-Verbose "Detected incompatible System.ClientModel version $clientModelVersion - will skip Azure.Core and Azure.Identity to avoid MissingMethodException"
}
}
# Check if SqlServer's older SqlClient is loaded (which bundles incompatible System.ClientModel)
# SqlClient 5.x from SqlServer module uses System.ClientModel 1.0.x
# Our Azure.Core requires System.ClientModel 1.1+
if (-not $script:hasIncompatibleClientModel) {
$existingSqlClient = $script:loadedAssemblies | Where-Object { $_.GetName().Name -eq 'Microsoft.Data.SqlClient' }
if ($existingSqlClient) {
$sqlClientVersion = $existingSqlClient.GetName().Version
# SqlClient 5.x bundles older System.ClientModel; 6.x bundles compatible versions
if ($sqlClientVersion.Major -lt 6) {
$script:hasIncompatibleClientModel = $true
Write-Verbose "Detected SqlClient $sqlClientVersion (pre-6.0) which uses incompatible System.ClientModel - will skip Azure.Core and Azure.Identity to avoid MissingMethodException"
}
}
}
}
# Check if SqlClient is already loaded when AvoidConflicts is set
$skipSqlClient = $false
if ($AvoidConflicts) {
$existingAssembly = $script:loadedAssemblies | Where-Object { $_.GetName().Name -eq 'Microsoft.Data.SqlClient' }
if ($existingAssembly) {
$skipSqlClient = $true
Write-Verbose "Skipping Microsoft.Data.SqlClient.dll - already loaded"
}
}
if (-not $skipSqlClient) {
try {
Import-Module $sqlclient
} catch {
throw "Couldn't import $sqlclient | $PSItem"
}
}
if ($PSVersionTable.PSEdition -eq "Core") {
$names = @(
'Microsoft.SqlServer.Server',
'Azure.Core',
'Azure.Identity',
'Microsoft.IdentityModel.Abstractions',
'Microsoft.SqlServer.Dac',
'Microsoft.SqlServer.Dac.Extensions',
'Microsoft.Data.Tools.Utilities',
'Microsoft.Data.Tools.Schema.Sql',
'Microsoft.SqlServer.TransactSql.ScriptDom',
'Microsoft.SqlServer.Smo',
'Microsoft.SqlServer.SmoExtended',
'Microsoft.SqlServer.SqlWmiManagement',
'Microsoft.SqlServer.WmiEnum',
'Microsoft.SqlServer.Management.RegisteredServers',
'Microsoft.SqlServer.Management.Collector',
'Microsoft.SqlServer.Management.XEvent',
'Microsoft.SqlServer.Management.XEventDbScoped',
'Microsoft.SqlServer.XEvent.XELite'
)
} else {
$names = @(
'Azure.Core',
'Azure.Identity',
'Microsoft.IdentityModel.Abstractions',
'Microsoft.SqlServer.Dac',
'Microsoft.SqlServer.Dac.Extensions',
'Microsoft.Data.Tools.Utilities',
'Microsoft.Data.Tools.Schema.Sql',
'Microsoft.SqlServer.TransactSql.ScriptDom',
'Microsoft.SqlServer.Smo',
'Microsoft.SqlServer.SmoExtended',
'Microsoft.SqlServer.SqlWmiManagement',
'Microsoft.SqlServer.WmiEnum',
'Microsoft.SqlServer.Management.RegisteredServers',
'Microsoft.SqlServer.Management.IntegrationServices',
'Microsoft.SqlServer.Management.Collector',
'Microsoft.SqlServer.Management.XEvent',
'Microsoft.SqlServer.Management.XEventDbScoped',
'Microsoft.SqlServer.XEvent.XELite'
)
}
if ($Env:SMODefaultModuleName) {
# then it's DSC, load other required assemblies
$names += "Microsoft.AnalysisServices.Core"
$names += "Microsoft.AnalysisServices"
$names += "Microsoft.AnalysisServices.Tabular"
$names += "Microsoft.AnalysisServices.Tabular.Json"
}
# XEvent stuff kills CI/CD
if ($PSVersionTable.OS -match "ARM64") {
$names = $names | Where-Object { $PSItem -notmatch "XE" }
}
#endregion Names
# Build string of loaded assembly names once for efficient checking
$script:loadedAssemblyNames = $script:loadedAssemblies.FullName | Out-String
try {
$null = Import-Module ([IO.Path]::Combine($script:libraryroot, "third-party", "bogus", "Bogus.dll"))
} catch {
Write-Error "Could not import $assemblyPath : $($_ | Out-String)"
}
foreach ($name in $names) {
$x64only = 'Microsoft.SqlServer.Replication', 'Microsoft.SqlServer.XEvent.Linq', 'Microsoft.SqlServer.BatchParser', 'Microsoft.SqlServer.Rmo', 'Microsoft.SqlServer.BatchParserClient'
if ($name -in $x64only -and $env:PROCESSOR_ARCHITECTURE -eq "x86") {
Write-Verbose -Message "Skipping $name. x86 not supported for this library."
continue
}
# Skip Azure.Core and Azure.Identity if System.ClientModel is incompatible
# These assemblies depend on System.ClientModel 1.1+ which has breaking API changes
if ($script:hasIncompatibleClientModel -and $name -in @('Azure.Core', 'Azure.Identity')) {
Write-Verbose "Skipping $name.dll - incompatible System.ClientModel already loaded"
continue
}
# Check if assembly is already loaded (always check to avoid duplicate loads)
if ($script:loadedAssemblyNames.Contains("$name,")) {
if ($AvoidConflicts) {
Write-Verbose "Skipping $name.dll - already loaded"
}
continue
}
# Load the assembly
$assemblyPath = [IO.Path]::Combine($script:libraryroot, "lib", "$name.dll")
try {
$null = Import-Module $assemblyPath
} catch {
Write-Error "Could not import $assemblyPath : $($_ | Out-String)"
}
}
# Keep the assembly resolver registered for Windows PowerShell
# It's needed at runtime when SMO and other assemblies try to resolve dependencies
# The resolver handles version mismatches (e.g., SMO requesting SqlClient 5.0.0.0 when 6.0.2 is loaded)
if ($PSVersionTable.PSEdition -ne "Core" -and $redirector) {
# Store the redirector in script scope so it stays alive and can be accessed if needed
$script:assemblyRedirector = $redirector
}