functions/Copy-SqlLogin.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
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
Function Copy-SqlLogin
{
<#
.SYNOPSIS
Migrates logins from source to destination SQL Servers. Supports SQL Server versions 2000 and above.

.DESCRIPTION
SQL Server 2000: Migrates logins with SIDs, passwords, server roles and database roles.

SQL Server 2005 & above: Migrates logins with SIDs, passwords, defaultdb, server roles & securables,
database permissions & securables, login attributes (enforce password policy, expiration, etc)

The login hash algorithm changed in SQL Server 2012, and is not backwards compatible with previous SQL
versions. This means that while SQL Server 2000 logins can be migrated to SQL Server 2012, logins
created in SQL Server 2012 can only be migrated to SQL Server 2012 and above.

THIS CODE IS PROVIDED "AS IS", WITH NO WARRANTIES.

.PARAMETER Source
Source SQL Server.You must have sysadmin access and server version must be SQL Server version 2000 or greater.

.PARAMETER Destination
Destination SQL Server. You must have sysadmin access and server version must be SQL Server version 2000 or greater.

.PARAMETER SourceSqlCredential
Allows you to login to servers using SQL Logins as opposed to Windows Auth/Integrated/Trusted. To use:

$scred = Get-Credential, then pass $scred object to the -SourceSqlCredential parameter.

Windows Authentication will be used if DestinationSqlCredential is not specified. SQL Server does not accept Windows credentials being passed as credentials.     
To connect as a different Windows user, run PowerShell as that user.

.PARAMETER DestinationSqlCredential
Allows you to login to servers using SQL Logins as opposed to Windows Auth/Integrated/Trusted. To use:

$dcred = Get-Credential, then pass this $dcred to the -DestinationSqlCredential parameter.

Windows Authentication will be used if DestinationSqlCredential is not specified. SQL Server does not accept Windows credentials being passed as credentials.     
To connect as a different Windows user, run PowerShell as that user.

.PARAMETER Exclude
Excludes specified logins. This list is auto-populated for tab completion.

.PARAMETER Login
Migrates ONLY specified logins. This list is auto-populated for tab completion. Multiple logins allowed.

.PARAMETER SyncOnly
Syncs only SQL Server login permissions, roles, etc. Does not add or drop logins or users. If a matching login does not exist on the destination, the login will be skipped.
Credential removal not currently supported for Syncs. TODO: Application role sync

.PARAMETER Force
Force drops and recreates logins. Logins that own jobs cannot be dropped at this time.

.NOTES
Author: Chrissy LeMaire (@cl), netnerds.net
Requires: sysadmin access on SQL Servers

dbatools PowerShell module (https://dbatools.io, clemaire@gmail.com)
Copyright (C) 2016 Chrissy LeMaire

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.

.LINK
https://dbatools.io/Copy-SqlLogin

.EXAMPLE
Copy-SqlLogin -Source sqlserver2014a -Destination sqlcluster -Force

Copies all logins from source server to destination server. If a SQL login on source exists on the destination,
the destination login will be dropped and recreated.

.EXAMPLE
Copy-SqlLogin -Source sqlserver2014a -Destination sqlcluster -Exclude realcajun -SourceSqlCredential $scred -DestinationSqlCredential $dcred

Authenticates to SQL Servers using SQL Authentication.

Copies all logins except for realcajun. If a login already exists on the destination, the login will not be migrated.

.EXAMPLE
Copy-SqlLogin -Source sqlserver2014a -Destination sqlcluster -Login realcajun, netnerds -force

Copies ONLY logins netnerds and realcajun. If login realcajun or netnerds exists on the destination, they will be dropped and recreated.

.EXAMPLE
Copy-SqlLogin -Source sqlserver2014a -Destination sqlcluster -SyncOnly

Syncs only SQL Server login permissions, roles, etc. Does not add or drop logins or users. If a matching login does not exist on the destination, the login will be skipped.


.NOTES
Author: Chrissy LeMaire (@cl), netnerds.net
Requires: sysadmin access on SQL Servers
Limitations: Does not support Application Roles yet

.LINK
https://gallery.technet.microsoft.com/scriptcenter/Fully-TransferMigrate-Sql-25a0cf05

#>

    
    [CmdletBinding(SupportsShouldProcess = $true)]
    Param (
        [parameter(Mandatory = $true, ValueFromPipeline = $true)]
        [object]$Source,
        [parameter(Mandatory = $true)]
        [object]$Destination,
        [object]$SourceSqlCredential,
        [object]$DestinationSqlCredential,
        [switch]$SyncOnly,
        [switch]$Force,
        [parameter(ValueFromPipeline = $true, DontShow)]
        [object]$pipelogin
    )
    
    DynamicParam { if ($source) { return Get-ParamSqlLogins -SqlServer $source -SqlCredential $SourceSqlCredential } }
    
    BEGIN
    {
        
        Function Copy-Login
        {
<#
 .SYNOPSIS
 Internal function
#>
            
            [cmdletbinding(SupportsShouldProcess = $true)]
            param (
                [Parameter(Mandatory = $true)]
                [ValidateNotNullOrEmpty()]
                [object]$sourceserver,
                [Parameter(Mandatory = $true)]
                [ValidateNotNullOrEmpty()]
                [object]$destserver,
                [Parameter()]
                [string[]]$Logins,
                [Parameter()]
                [string[]]$Exclude,
                [Parameter()]
                [bool]$Force
            )
            
            if ($sourceserver.versionMajor -gt 10 -and $destserver.versionMajor -lt 11)
            {
                throw "SQL login migration from SQL Server version $($sourceserver.versionMajor) to $($destserver.versionMajor) not supported. Halting."
            }
            
            $source = $sourceserver.DomainInstanceName
            $destination = $destserver.DomainInstanceName
            
            foreach ($sourcelogin in $sourceserver.logins)
            {
                
                $username = $sourcelogin.name
                if ($Logins -ne $null -and $Logins -notcontains $username) { continue }
                if ($Exclude -contains $username -or $username.StartsWith("##") -or $username -eq 'sa') { Write-Output "Skipping $username"; continue }
                $servername = Get-NetBiosName $sourceserver
                
                $currentlogin = $sourceserver.ConnectionContext.truelogin
                
                if ($currentlogin -eq $username -and $force)
                {
                    If ($Pscmdlet.ShouldProcess("console", "Stating $username is skipped because it is performing the migration."))
                    {
                        Write-Warning "Cannot drop login performing the migration. Skipping"
                    }
                    continue
                }
                
                $userbase = ($username.Split("\")[0]).ToLower()
                if ($servername -eq $userbase -or $username.StartsWith("NT "))
                {
                    If ($Pscmdlet.ShouldProcess("console", "Stating $username is skipped because it is a local machine name."))
                    {
                        Write-Output "Stating $username is skipped because it is a local machine name."
                    }
                    continue
                }
                
                if (($login = $destserver.Logins.Item($username)) -ne $null -and !$force)
                {
                    If ($Pscmdlet.ShouldProcess("console", "Stating $username is skipped because it exists at destination."))
                    {
                        Write-Output "$username already exists in destination. Use -force to drop and recreate."
                    }
                    continue
                }
                
                if ($login -ne $null -and $force)
                {
                    if ($username -eq $destserver.ServiceAccount) { Write-Warning "$username is the destination service account. Skipping drop."; continue }
                    If ($Pscmdlet.ShouldProcess($destination, "Dropping $username"))
                    {
                        # Kill connections, delete user
                        Write-Output "Attempting to migrate $username"
                        Write-Output "Force was specified. Attempting to drop $username on $destination"
                        try
                        {
                            $destserver.EnumProcesses() | Where { $_.Login -eq $username } | ForEach-Object { $destserver.KillProcess($_.spid) }
                            
                            $owneddbs = $destserver.Databases | Where { $_.Owner -eq $username }
                            foreach ($owneddb in $owneddbs)
                            {
                                Write-Output "Changing database owner for $($owneddb.name) from $username to sa"
                                $owneddb.SetOwner('sa')
                                $owneddb.Alter()
                            }
                            
                            $ownedjobs = $destserver.JobServer.Jobs | Where { $_.OwnerLoginName -eq $username }
                            foreach ($ownedjob in $ownedjobs)
                            {
                                Write-Output "Changing job owner for $($ownedjob.name) from $username to sa"
                                $ownedjob.set_OwnerLoginName('sa')
                                $ownedjob.Alter()
                            }
                            
                            $login.drop()
                            Write-Output "Successfully dropped $username on $destination"
                        }
                        catch
                        {
                            $ex = $_.Exception.Message
                            if ($ex -ne $null) { $ex.trim() }
                            Write-Error "Could not drop $username`: $ex"
                            Write-Exception $_
                            continue
                        }
                    }
                }
                
                If ($Pscmdlet.ShouldProcess($destination, "Adding SQL login $username"))
                {
                    Write-Output "Attempting to add $username to $destination"
                    $destlogin = New-Object Microsoft.SqlServer.Management.Smo.Login($destserver, $username)
                    Write-Output "Setting $username SID to source username SID"
                    $destlogin.set_Sid($sourcelogin.get_Sid())
                    
                    $defaultdb = $sourcelogin.DefaultDatabase
                    Write-Output "Setting login language to $($sourcelogin.Language)"
                    $destlogin.Language = $sourcelogin.Language
                    
                    if ($destserver.databases[$defaultdb] -eq $null)
                    {
                        Write-Warning "$defaultdb does not exist on destination. Setting defaultdb to master."
                        $defaultdb = "master"
                    }
                    Write-Output "Set $username defaultdb to $defaultdb"
                    $destlogin.DefaultDatabase = $defaultdb
                    
                    $checkexpiration = "ON"; $checkpolicy = "ON"
                    if ($sourcelogin.PasswordPolicyEnforced -eq $false) { $checkpolicy = "OFF" }
                    if (!$sourcelogin.PasswordExpirationEnabled) { $checkexpiration = "OFF" }
                    
                    $destlogin.PasswordPolicyEnforced = $sourcelogin.PasswordPolicyEnforced
                    $destlogin.PasswordExpirationEnabled = $sourcelogin.PasswordExpirationEnabled
                    
                    # Attempt to add SQL Login User
                    if ($sourcelogin.LoginType -eq "SqlLogin")
                    {
                        $destlogin.LoginType = "SqlLogin"
                        $sourceloginname = $sourcelogin.name
                        
                        switch ($sourceserver.versionMajor)
                        {
                            0 { $sql = "SELECT convert(varbinary(256),password) as hashedpass FROM master.dbo.syslogins WHERE loginname='$sourceloginname'" }
                            8 { $sql = "SELECT convert(varbinary(256),password) as hashedpass FROM dbo.syslogins WHERE name='$sourceloginname'" }
                            9 { $sql = "SELECT convert(varbinary(256),password_hash) as hashedpass FROM sys.sql_logins where name='$sourceloginname'" }
                            default
                            {
                                $sql = "SELECT CAST(CONVERT(varchar(256), CAST(LOGINPROPERTY(name,'PasswordHash')
      AS varbinary (256)), 1) AS nvarchar(max)) as hashedpass FROM sys.server_principals
      WHERE principal_id = $($sourcelogin.id)"

                            }
                        }
                        
                        try { $hashedpass = $sourceserver.ConnectionContext.ExecuteScalar($sql) }
                        catch
                        {
                            $hashedpassdt = $sourceserver.databases['master'].ExecuteWithResults($sql)
                            $hashedpass = $hashedpassdt.Tables[0].Rows[0].Item(0)
                        }
                        
                        if ($hashedpass.gettype().name -ne "String")
                        {
                            $passtring = "0x"; $hashedpass | % { $passtring += ("{0:X}" -f $_).PadLeft(2, "0") }
                            $hashedpass = $passtring
                        }
                        
                        try
                        {
                            $destlogin.Create($hashedpass, [Microsoft.SqlServer.Management.Smo.LoginCreateOptions]::IsHashed)
                            $destlogin.refresh()
                            Write-Output "Successfully added $username to $destination"
                        }
                        catch
                        {
                            try
                            {
                                $sid = "0x"; $sourcelogin.sid | % { $sid += ("{0:X}" -f $_).PadLeft(2, "0") }
                                $sqlfailsafe = "CREATE LOGIN [$username] WITH PASSWORD = $hashedpass HASHED, SID = $sid,
      DEFAULT_DATABASE = [$defaultdb], CHECK_POLICY = $checkpolicy, CHECK_EXPIRATION = $checkexpiration"

                                $null = $destserver.ConnectionContext.ExecuteNonQuery($sqlfailsafe)
                                $destlogin = $destserver.logins[$username]
                                Write-Output "Successfully added $username to $destination"
                            }
                            catch
                            {
                                Write-Warning "Failed to add $username to $destination`: $_"
                                Write-Exception $_
                                continue
                            }
                        }
                    }
                    # Attempt to add Windows User
                    elseif ($sourcelogin.LoginType -eq "WindowsUser" -or $sourcelogin.LoginType -eq "WindowsGroup")
                    {
                        Write-Output "Adding as login type $($sourcelogin.LoginType)"
                        $destlogin.LoginType = $sourcelogin.LoginType
                        Write-Output "Setting language as $($sourcelogin.Language)"
                        $destlogin.Language = $sourcelogin.Language
                        
                        try
                        {
                            $destlogin.Create()
                            $destlogin.Refresh()
                            Write-Output "Successfully added $username to $destination"
                        }
                        catch
                        {
                            Write-Warning "Failed to add $username to $destination"
                            Write-Exception $_
                            continue
                        }
                    }
                    # This script does not currently support certificate mapped or asymmetric key users.
                    else
                    {
                        Write-Warning "$($sourcelogin.LoginType) logins not supported. $($sourcelogin.name) skipped."
                        continue
                    }
                    
                    if ($sourcelogin.IsDisabled)
                    {
                        try { $destlogin.Disable() }
                        catch { Write-Warning "$username disabled on source, but could not be disabled on destination."; Write-Exception $_ }
                    }
                    if ($sourcelogin.DenyWindowsLogin)
                    {
                        try { $destlogin.DenyWindowsLogin = $true }
                        catch { Write-Warning "$username denied login on source, but could not be denied login on destination."; Write-Exception $_ }
                    }
                }
                If ($Pscmdlet.ShouldProcess($destination, "Updating SQL login $username permissions"))
                {
                    Update-SqlPermissions -sourceserver $sourceserver -sourcelogin $sourcelogin -destserver $destserver -destlogin $destlogin
                }
            }
            
        }
        
        Function Update-SqlPermissions
        {
 <#
 
.SYNOPSIS
 Internal function. Updates permission sets, roles, database mappings on server and databases

 #>

            [CmdletBinding()]
            param (
                [Parameter(Mandatory = $true)]
                [ValidateNotNullOrEmpty()]
                [object]$sourceserver,
                [Parameter(Mandatory = $true)]
                [ValidateNotNullOrEmpty()]
                [object]$sourcelogin,
                [Parameter(Mandatory = $true)]
                [ValidateNotNullOrEmpty()]
                [object]$destserver,
                [Parameter(Mandatory = $true)]
                [ValidateNotNullOrEmpty()]
                [object]$destlogin
            )
            
            $destination = $destserver.DomainInstanceName
            $source = $sourceserver.DomainInstanceName
            $username = $sourcelogin.name
            
            # Server Roles: sysadmin, bulklogin, etc
            foreach ($role in $sourceserver.roles)
            {
                $rolename = $role.name
                $destrole = $destserver.roles[$rolename]
                if ($destrole -ne $null)
                {
                    try { $destrolemembers = $destrole.EnumMemberNames() }
                    catch { $destrolemembers = $destrole.EnumServerRoleMembers() }
                }
                try { $rolemembers = $role.EnumMemberNames() }
                catch { $rolemembers = $role.EnumServerRoleMembers() }
                if ($rolemembers -contains $username)
                {
                    if ($destrole -ne $null)
                    {
                        If ($Pscmdlet.ShouldProcess($destination, "Adding $username to$rolename server role"))
                        {
                            try
                            {
                                $destrole.AddMember($username)
                                Write-Output "Added $username to$rolename server role."
                            }
                            catch
                            {
                                Write-Warning "Failed to add $username to$rolename server role."
                                Write-Exception $_
                            }
                        }
                    }
                }
                
                # Remove for Syncs
                if ($rolemembers -notcontains $username -and $destrolemembers -contains $username -and $destrole -ne $null)
                {
                    If ($Pscmdlet.ShouldProcess($destination, "Adding $username to$rolename server role"))
                    {
                        try
                        {
                            $destrole.DropMember($username)
                            Write-Output "Removed $username from $destrolename server role on $($destserver.name)."
                        }
                        catch
                        {
                            Write-Warning "Failed to remove $username from $destrolename server role on $($destserver.name)."
                            Write-Exception $_
                        }
                    }
                }
            }
            
            $ownedjobs = $sourceserver.JobServer.Jobs | Where { $_.OwnerLoginName -eq $username }
            foreach ($ownedjob in $ownedjobs)
            {
                if ($destserver.JobServer.Jobs[$ownedjob.name] -ne $null)
                {
                    If ($Pscmdlet.ShouldProcess($destination, "Changing job owner to $username for $($ownedjob.name)"))
                    {
                        try
                        {
                            Write-Output "Changing job owner to $username for $($ownedjob.name)"
                            $destownedjob = $destserver.JobServer.Jobs | Where { $_.name -eq $ownedjobs.name }
                            $destownedjob.set_OwnerLoginName($username)
                            $destownedjob.Alter()
                        }
                        catch
                        {
                            Write-Warning "Could not change job owner for $($ownedjob.name)"
                            Write-Exception $_
                        }
                    }
                }
            }
            
            if ($sourceserver.versionMajor -ge 9 -and $destserver.versionMajor -ge 9)
            {
                # These operations are only supported by SQL Server 2005 and above.
                # Securables: Connect SQL, View any database, Administer Bulk Operations, etc.
                
                $perms = $sourceserver.EnumServerPermissions($username)
                foreach ($perm in $perms)
                {
                    $permstate = $perm.permissionstate
                    if ($permstate -eq "GrantWithGrant") { $grantwithgrant = $true; $permstate = "grant" }
                    else { $grantwithgrant = $false }
                    $permset = New-Object Microsoft.SqlServer.Management.Smo.ServerPermissionSet($perm.permissiontype)
                    If ($Pscmdlet.ShouldProcess($destination, "Performing $permstate on $($perm.permissiontype) for $username"))
                    {
                        try
                        {
                            $destserver.PSObject.Methods[$permstate].Invoke($permset, $username, $grantwithgrant)
                            Write-Output "Successfully performed $permstate $($perm.permissiontype) to $username"
                        }
                        catch
                        {
                            Write-Warning "Failed to $permstate $($perm.permissiontype) to $username"
                            Write-Exception $_
                        }
                    }
                    
                    # for Syncs
                    $destperms = $destserver.EnumServerPermissions($username)
                    foreach ($perm in $destperms)
                    {
                        $permstate = $perm.permissionstate
                        $sourceperm = $perms | Where-Object { $_.PermissionType -eq $perm.Permissiontype -and $_.PermissionState -eq $permstate }
                        if ($sourceperm -eq $null)
                        {
                            If ($Pscmdlet.ShouldProcess($destination, "Performing Revoke on $($perm.permissiontype) for $username"))
                            {
                                try
                                {
                                    $permset = New-Object Microsoft.SqlServer.Management.Smo.ServerPermissionSet($perm.permissiontype)
                                    if ($permstate -eq "GrantWithGrant") { $grantwithgrant = $true; $permstate = "grant" }
                                    else { $grantwithgrant = $false }
                                    $destserver.PSObject.Methods["Revoke"].Invoke($permset, $username, $false, $grantwithgrant)
                                    Write-Output "Successfully revoked $($perm.permissiontype) from $username"
                                }
                                catch
                                {
                                    Write-Warning "Failed to revoke $($perm.permissiontype) from $username"
                                    Write-Exception $_
                                }
                            }
                        }
                    }
                }
                
                # Credential mapping. Credential removal not currently supported for Syncs.
                $logincredentials = $sourceserver.credentials | Where-Object { $_.Identity -eq $sourcelogin.name }
                foreach ($credential in $logincredentials)
                {
                    if ($destserver.Credentials[$credential.name] -eq $null)
                    {
                        If ($Pscmdlet.ShouldProcess($destination, "Adding $($credential.name) to $username"))
                        {
                            try
                            {
                                $newcred = New-Object Microsoft.SqlServer.Management.Smo.Credential($destserver, $credential.name)
                                $newcred.identity = $sourcelogin.name
                                $newcred.Create()
                                Write-Output "Successfully created credential for $username"
                            }
                            catch
                            {
                                Write-Warning "Failed to create credential for $username"
                                Write-Exception $_
                            }
                        }
                    }
                }
            }
            
            if ($destserver.versionMajor -lt 9) { Write-Warning "Database mappings skipped when destination is SQL Server 2000"; continue }
            
            # For Sync, if info doesn't exist in EnumDatabaseMappings, then no big deal.
            foreach ($db in $destlogin.EnumDatabaseMappings())
            {
                $dbname = $db.dbname
                $destdb = $destserver.databases[$dbname]
                $sourcedb = $sourceserver.databases[$dbname]
                $dbusername = $db.username; $dblogin = $db.loginName
                
                if ($sourcedb -ne $null)
                {
                    if ($sourcedb.users[$dbusername] -eq $null -and $destdb.users[$dbusername] -ne $null)
                    {
                        If ($Pscmdlet.ShouldProcess($destination, "Dropping $dbusername from $dbname on destination."))
                        {
                            try
                            {
                                $destdb.users[$dbusername].Drop()
                                Write-Output "Dropped user $dbusername (login: $dblogin) from $dbname on destination. User may own a schema."
                            }
                            catch
                            {
                                Write-Warning "Failed to drop $dbusername ($dblogin) from $dbname on destination."
                                Write-Exception $_
                            }
                        }
                    }
                    
                    # Remove user from role. Role removal not currently supported for Syncs.
                    # TODO: reassign if dbo, application roles
                    foreach ($destrole in $destdb.roles)
                    {
                        $destrolename = $destrole.name
                        $sourcerole = $sourcedb.roles[$destrolename]
                        if ($sourcerole -ne $null)
                        {
                            if ($sourcerole.EnumMembers() -notcontains $dbusername -and $destrole.EnumMembers() -contains $dbusername)
                            {
                                if ($dbusername -ne "dbo")
                                {
                                    If ($Pscmdlet.ShouldProcess($destination, "Dropping $username from $destrolename database role on $dbname"))
                                    {
                                        try
                                        {
                                            $destrole.DropMember($dbusername)
                                            $destdb.Alter()
                                            Write-Output "Dropped username $dbusername (login: $dblogin) from $destrolename on $destination"
                                        }
                                        catch
                                        {
                                            Write-Warning "Failed to remove $dbusername from $destrolename database role on $dbname."
                                            Write-Exception $_
                                        }
                                    }
                                }
                            }
                        }
                    }
                    
                    # Remove Connect, Alter Any Assembly, etc
                    $destperms = $destdb.EnumDatabasePermissions($username)
                    $perms = $sourcedb.EnumDatabasePermissions($username)
                    # for Syncs
                    foreach ($perm in $destperms)
                    {
                        $permstate = $perm.permissionstate
                        $sourceperm = $perms | Where-Object { $_.PermissionType -eq $perm.Permissiontype -and $_.PermissionState -eq $permstate }
                        if ($sourceperm -eq $null)
                        {
                            If ($Pscmdlet.ShouldProcess($destination, "Performing Revoke on $($perm.permissiontype) for $username on $dbname on $destination"))
                            {
                                try
                                {
                                    $permset = New-Object Microsoft.SqlServer.Management.Smo.DatabasePermissionSet($perm.permissiontype)
                                    if ($permstate -eq "GrantWithGrant") { $grantwithgrant = $true; $permstate = "grant" }
                                    else { $grantwithgrant = $false }
                                    $destdb.PSObject.Methods["Revoke"].Invoke($permset, $username, $false, $grantwithgrant)
                                    Write-Output "Successfully revoked $($perm.permissiontype) from $username on $dbname on $destination"
                                }
                                catch
                                {
                                    Write-Warning "Failed to revoke $($perm.permissiontype) from $username on $dbname on $destination"
                                    Write-Exception $_
                                }
                            }
                        }
                    }
                }
            }
            
            # Adding database mappings and securables
            foreach ($db in $sourcelogin.EnumDatabaseMappings())
            {
                $dbname = $db.dbname
                $destdb = $destserver.databases[$dbname]
                $sourcedb = $sourceserver.databases[$dbname]
                $dbusername = $db.username; $dblogin = $db.loginName
                
                if ($destdb -ne $null)
                {
                    if ($destdb.users[$dbusername] -eq $null)
                    {
                        If ($Pscmdlet.ShouldProcess($destination, "Adding $dbusername to $dbname"))
                        {
                            $sql = $sourceserver.databases[$dbname].users[$dbusername].script() | Out-String
                            $sql = $sql -replace "'$source'", "'$destination'"
                            try
                            {
                                $destdb.ExecuteNonQuery($sql)
                                Write-Output "Added user $dbusername (login: $dblogin) to $dbname"
                            }
                            catch
                            {
                                Write-Warning "Failed to add $dbusername ($dblogin) to $dbname on $destination."
                                Write-Exception $_
                            }
                        }
                    }
                    
                    # Db owner
                    If ($sourcedb.owner -eq $username)
                    {
                        If ($Pscmdlet.ShouldProcess($destination, "Changing $dbname dbowner to $username"))
                        {
                            try
                            {
                                $result = Update-SqlDbOwner $sourceserver $destserver -dbname $dbname
                                if ($result -eq $true)
                                {
                                    Write-Output "Changed $($destdb.name) owner to $($sourcedb.owner)."
                                }
                                else { Write-Warning "Failed to update $($destdb.name) owner to $($sourcedb.owner)." }
                            }
                            catch { Write-Warning "Failed to update $($destdb.name) owner to $($sourcedb.owner)." }
                        }
                    }
                    
                    # Database Roles: db_owner, db_datareader, etc
                    foreach ($role in $sourcedb.roles)
                    {
                        if ($role.EnumMembers() -contains $username)
                        {
                            $destdbrole = $destdb.roles[$rolename]
                            if ($destdbrole -ne $null -and $dbusername -ne "dbo" -and $destdbrole.EnumMembers() -notcontains $username)
                            {
                                If ($Pscmdlet.ShouldProcess($destination, "Adding $username to$rolename database role on $dbname"))
                                {
                                    try
                                    {
                                        $destdbrole.AddMember($username)
                                        $destdb.Alter()
                                        Write-Output "Added $username to$rolename database role on $dbname."
                                        
                                    }
                                    catch
                                    {
                                        Write-Warning "Failed to add $username to$rolename database role on $dbname."
                                        Write-Exception $_
                                    }
                                }
                            }
                        }
                    }
                    
                    # Connect, Alter Any Assembly, etc
                    $perms = $sourcedb.EnumDatabasePermissions($username)
                    foreach ($perm in $perms)
                    {
                        $permstate = $perm.permissionstate
                        if ($permstate -eq "GrantWithGrant") { $grantwithgrant = $true; $permstate = "grant" }
                        else { $grantwithgrant = $false }
                        $permset = New-Object Microsoft.SqlServer.Management.Smo.DatabasePermissionSet($perm.permissiontype)
                        If ($Pscmdlet.ShouldProcess($destination, "Performing $permstate on $($perm.permissiontype) for $username on $dbname"))
                        {
                            try
                            {
                                $destdb.PSObject.Methods[$permstate].Invoke($permset, $username, $grantwithgrant)
                                Write-Output "Successfully performed $permstate $($perm.permissiontype) to $username on $dbname"
                            }
                            catch
                            {
                                Write-Warning "Failed to perform $permstate on $($perm.permissiontype) for $username on $dbname."
                                Write-Exception $_
                            }
                        }
                    }
                }
            }
        }
        
        Function Sync-Only
        {
<#
.SYNOPSIS
Internal function. Skips migration, and just syncs permission sets, roles, database mappings on server and databases

#>

            [CmdletBinding()]
            param (
                [Parameter(Mandatory = $true)]
                [ValidateNotNullOrEmpty()]
                [object]$sourceserver,
                [object]$destserver,
                [array]$Logins,
                [array]$Exclude
            )
            
            $source = $sourceserver.DomainInstanceName; $destination = $destserver.DomainInstanceName
            $exclude | Where-Object { !([string]::IsNullOrEmpty($_)) } | ForEach-Object { $skippedlogin.Add($_, "Explicitly Skipped") }
            
            foreach ($sourcelogin in $sourceserver.logins)
            {
                
                $username = $sourcelogin.name
                $currentlogin = $sourceserver.ConnectionContext.truelogin
                if ($Logins -ne $null -and $Logins -notcontains $username) { continue }
                if ($exclude -contains $username -or $username.StartsWith("##") -or $username -eq 'sa') { continue }
                
                if ($currentlogin -eq $username)
                {
                    Write-Warning "Sync does not modify the permissions of the current user. Skipping."
                    continue
                }
                
                $servername = Get-NetBiosName $sourceserver
                $userbase = ($username.Split("\")[0]).ToLower()
                if ($servername -eq $userbase -or $username.StartsWith("NT ")) { continue }
                if (($destlogin = $destserver.Logins.Item($username)) -eq $null) { continue }
                
                Update-SqlPermissions -sourceserver $sourceserver -sourcelogin $sourcelogin -destserver $destserver -destlogin $destlogin
            }
        }
        
        if ($source -eq $destination) { throw "Source and Destination SQL Servers are the same. Quitting." }
        
        Write-Output "Attempting to connect to SQL Servers.."
        $sourceserver = Connect-SqlServer -SqlServer $Source -SqlCredential $SourceSqlCredential
        $destserver = Connect-SqlServer -SqlServer $Destination -SqlCredential $DestinationSqlCredential
        
        $source = $sourceserver.DomainInstanceName
        $destination = $destserver.DomainInstanceName
        
        if ($sourceserver.versionMajor -lt 8 -or $destserver.versionMajor -lt 8) { throw "SQL Server 7 and below not supported. Quitting." }
        
        $elapsed = [System.Diagnostics.Stopwatch]::StartNew()
        $started = Get-Date
        
        If ($Pscmdlet.ShouldProcess("console", "Showing time elapsed message"))
        {
            Write-Output "Migration started: $started"
        }
        
    }
    
    
    PROCESS
    {
        if ($pipelogin.Length -gt 0)
        {
            $Source = $pipelogin[0].parent.name
            $logins = $pipelogin.name
        }
        
    <# ----------------------------------------------------------
  Preps
 ---------------------------------------------------------- #>

        
        # Convert from RuntimeDefinedParameter object to regular array
        $Logins = $psboundparameters.Login
        $Exclude = $psboundparameters.Exclude
        
    <# ----------------------------------------------------------
  Run
 ---------------------------------------------------------- #>

        
        if ($SyncOnly)
        {
            Write-Output "Syncing Login Permissions";
            Sync-Only -sourceserver $sourceserver -destserver $destserver -Logins $Logins -Exclude $Exclude
            return
        }
        
        Write-Output "Attempting Login Migration";
        Copy-Login -sourceserver $sourceserver -destserver $destserver -Logins $Logins -Exclude $Exclude -Force $force
    }
    
    END
    {
        
        If ($Pscmdlet.ShouldProcess("console", "Showing time elapsed message"))
        {
            Write-Output "Login migration completed: $(Get-Date)"
            $totaltime = ($elapsed.Elapsed.toString().Split(".")[0])
            $sourceserver.ConnectionContext.Disconnect()
            $destserver.ConnectionContext.Disconnect()
            Write-Output "Total elapsed time: $totaltime"
        }
    }
}