Skip to content

Commit cd63a61

Browse files
Export-DbaUser - Use server version instead of db compat level for scripting
When no -DestinationVersion is specified, use the actual SQL Server instance version (VersionMajor) rather than the database compatibility level as the SMO scripting target. This fixes an error where databases on newer SQL Server instances (e.g., 2022) with a lower compatibility level (e.g., 120/SQL2014) could not export users that use features not available at the compat level, such as External users introduced in SQL Server 2016. Fixes #10343 (do Export-DbaUser) Co-authored-by: Andreas Jordan <andreasjordan@users.noreply.github.com>
1 parent 74a2d1a commit cd63a61

1 file changed

Lines changed: 26 additions & 2 deletions

File tree

public/Export-DbaUser.ps1

Lines changed: 26 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -216,6 +216,21 @@ function Export-DbaUser {
216216
'Version160' = 'SQLServer2022'
217217
}
218218

219+
# Maps SQL Server major version number to SMO scripting version string.
220+
# Used to resolve the actual server version when no DestinationVersion is specified,
221+
# since the database compatibility level may be lower than the server version.
222+
$serverVersionMap = @{
223+
8 = 'Version80'
224+
9 = 'Version90'
225+
10 = 'Version100'
226+
11 = 'Version110'
227+
12 = 'Version120'
228+
13 = 'Version130'
229+
14 = 'Version140'
230+
15 = 'Version150'
231+
16 = 'Version160'
232+
}
233+
219234
$eol = [System.Environment]::NewLine
220235

221236
}
@@ -232,8 +247,17 @@ function Export-DbaUser {
232247
foreach ($db in $InputObject) {
233248

234249
if ([string]::IsNullOrEmpty($destinationVersion)) {
235-
#Get compatibility level for scripting the objects
236-
$scriptVersion = $db.CompatibilityLevel
250+
# Use the actual server version rather than the database compatibility level.
251+
# The compatibility level may be lower than the server version (e.g., a SQL 2022
252+
# instance hosting a database at compat level 120/SQL2014). Scripting against
253+
# the lower compat level causes errors for features like External users that are
254+
# supported by the server but not recognised by older scripting targets.
255+
$serverMajorVersion = $db.Parent.VersionMajor
256+
if ($serverVersionMap.ContainsKey($serverMajorVersion)) {
257+
$scriptVersion = $serverVersionMap[$serverMajorVersion]
258+
} else {
259+
$scriptVersion = $db.CompatibilityLevel
260+
}
237261
} else {
238262
$scriptVersion = $versions[$destinationVersion]
239263
}

0 commit comments

Comments
 (0)