Snapshot.psm1

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
#region Get-ActiveDirectorySnapshot
Function Get-ActiveDirectorySnapshot
{
    <#
    .Synopsis
       Get the Active Directory snapshots.
    .DESCRIPTION
       Get the Active Directory snapshots on a domain controller.
    .EXAMPLE
        PS C:\> Get-ActiveDirectorySnapshot
 
        Identity Date SetID
        -------- ---- -----
        {B22E56F9-C4C5-49C2-A4EF-67A40DE21132} 7/9/2016 9:08:54 μμ {34987893-9D63-4955-968B-3000002789F5}
        {1DF443D2-9F27-41C4-9E32-950F557E9826} 7/9/2016 8:39:35 μμ {6D3802A3-BD22-4732-AE27-5FEC25EE1E01}
    #>


    [cmdletBinding()]

    Param
    (
        # The identity of the snapshot
        [Parameter(Mandatory=$false, 
                   ValueFromPipeline=$true,
                   ValueFromPipelineByPropertyName=$true, 
                   ValueFromRemainingArguments=$false, 
                   Position=0)]
        [string]$Identity,

        # The Active Directory Domain Controller
        [Parameter(Mandatory=$false, 
                   Position=1)]
        [string[]]$Server = $env:COMPUTERNAME
    )

    Begin {}

    Process
    {
        # Get the snapshots
        foreach($s in $Server)
        {
            $snapshots = Get-WmiObject Win32_ShadowCopy -ComputerName $Server |
                            Select-Object @{Name="Identity"; Expression={$_.Id}}, `
                                          @{Name="Date"; Expression={$_.ConvertToDateTime($_.InstallDate)}}, `
                                          @{Name="SetID"; Expression={$_.SetID}}, `
                                          @{Name="Mounted"; Expression={$_.ExposedLocally}}, `
                                          @{Name="MountPoint"; Expression={$_.ExposedName}}, `
                                          @{Name="Server"; Expression={$s}} |
                                Sort-Object -Property Install_Date -Descending

            # Return particular snapshot (if requested)
            if($Identity)
            {
                $snapshots |
                    Where-Object {$_.Identity -eq $Identity}
            }
            else
            {
                $snapshots
            }
        }
    }

    End {}
}
#endregion

#region New-ActiveDirectorySnapshot
Function New-ActiveDirectorySnapshot
{
    <#
    .Synopsis
       Create an Active Directory snapshot.
    .DESCRIPTION
       Create an Active Directory snapshot.
    .EXAMPLE
        PS C:\> New-ActiveDirectorySnapshot
 
        Identity Date SetID Server
        -------- ---- ----- ------
        {809B678A-7733-4011-ACD5-6... 17/6/2017 12:31:54 πμ {D69CF349-6EFD-4717-AB58-1... DC1
    #>


    [cmdletBinding(SupportsShouldProcess=$true,
                   ConfirmImpact='Medium')]

    Param
    (
        # The Active Directory Domain Controller
        [Parameter(Mandatory=$false, 
                   ValueFromPipeline=$true,
                   ValueFromPipelineByPropertyName=$true, 
                   ValueFromRemainingArguments=$false, 
                   Position=0)]        
        [string[]]$Server = $env:COMPUTERNAME
    )

    Begin {}

    Process
    {
        # Select the Domain Controller
        if(-Not $Server)
        {
            $Server = $env:COMPUTERNAME
        }

        foreach($s in $Server)
        {
            if($PSCmdlet.ShouldProcess($s, "Create Active Directory snapshot"))
            {
                $id = Invoke-Command -ComputerName $s `
                           -ScriptBlock {
                                $pinfo = New-Object System.Diagnostics.ProcessStartInfo
                                $pinfo.FileName = "ntdsutil"
                                $pinfo.RedirectStandardError = $true
                                $pinfo.RedirectStandardOutput = $true
                                $pinfo.RedirectStandardInput = $true
                                $pinfo.UseShellExecute = $false
                                $pinfo.CreateNoWindow = $true
    
                                $p = New-Object System.Diagnostics.Process
                                $p.StartInfo = $pinfo
                                $p.Start() | Out-Null

                                $p.StandardInput.WriteLine("Activate Instance NTDS")
                                $p.StandardInput.WriteLine("snapshot")
                                $p.StandardInput.WriteLine("create")
                                $p.StandardInput.WriteLine("quit")
                                $p.StandardInput.WriteLine("quit")
                                $p.WaitForExit()
    
                                $stdout = $p.StandardOutput.ReadToEnd()
                                $stderr = $p.StandardError.ReadToEnd()
            
                                if($p.ExitCode -ne 0)
                                {
                                    Write-Error $stderr
                                    return $null
                                }
                                else
                                {
                                    [string]$data = $stdout
                                    $startIndex = $data.IndexOf("Snapshot set") + 13 
                                    $stopIndex = $data.IndexOf("generated") - 1
                                    $data = $data.Substring($startIndex, $stopIndex - $startIndex)
                                    $data
                                }
                            }
                if($id -ne $null)
                {
                    Get-ActiveDirectorySnapshot -Server $s |
                        Where-Object {$_.SetID -eq $id}
                
                }
                else
                {
                    Write-Error "Failed to create Active Directory snapshot on server $s"
                }
            }
        }
    }

    End {}
}
#endregion

#region Remove-ActiveDirectorySnapshot
Function Remove-ActiveDirectorySnapshot
{
    <#
    .Synopsis
       Short description
    .DESCRIPTION
       Long description
    .EXAMPLE
       Example of how to use this cmdlet
    .EXAMPLE
       Another example of how to use this cmdlet
    #>


    [CmdletBinding(SupportsShouldProcess=$true, 
                  ConfirmImpact='High')]

    Param
    (
        # The identity of the snapshot to remove.
        [Parameter(Mandatory=$true, 
                   ValueFromPipeline=$true,
                   ValueFromPipelineByPropertyName=$true, 
                   ValueFromRemainingArguments=$false, 
                   Position=0)]
        [string[]]$Identity,

        # The Active Directory Domain Controller.
        [Parameter(Mandatory=$false, 
                   Position=1)]
        [string]$Server = $env:COMPUTERNAME
    )

    Begin {}

    Process
    {
        foreach($i in $Identity)
        {
            if($PSCmdlet.ShouldProcess($i, "Remove Active Directory snapshot"))
            {
                $snapshot = Get-WmiObject Win32_ShadowCopy -ComputerName $Server |
                    Where-Object {$_.Id -eq $Identity}

                if($snapshot)
                {
                    $snapshot.Delete()
                }
                else
                {
                    Write-Error "Could not find snaphot!"
                }
            }
        }
    }
    
    End
    {
    }                
}
#endregion

#region Mount-ActiveDirectorySnapshot
function Mount-ActiveDirectorySnapshot
{
    <#
    .Synopsis
       Mount an Active Directory snapshot.
    .DESCRIPTION
       Mount an Active Directory snapshot and use dsamain.exe to load it.
    .EXAMPLE
        PS C:\> Get-ActiveDirectorySnapshot
 
        Identity : {CAE74093-6422-42D5-AB1B-988C418E1560}
        Date : 17/6/2017 11:42:37 πμ
        SetID : {7772C6CE-F375-49B9-BC28-16F965B4E55C}
        Mounted : False
        MountPoint :
        Server : DC1
 
        PS C:\> Mount-ActiveDirectorySnapshot -Identity "{CAE74093-6422-42D5-AB1B-988C418E1560}" -Port 33389
 
        Mount the Active Directory snapshot with id {CAE74093-6422-42D5-AB1B-988C418E1560} on port 33389
    .EXAMPLE
        PS C:\> Get-ActiveDirectorySnapshot | Sort-Object -Property Date -Descending | Select-Object -First 1 | Mount-ActiveDirectorySnapshot -Port 33389 -Verbose
        VERBOSE: Performing the operation "Mount Active Directory snapshot" on target "{CAE74093-6422-42D5-AB1B-988C418E1560}".
        VERBOSE: Loading database: C:\$SNAP_201706171142_VOLUMEC$\Windows\NTDS\ntds.dit
        VERBOSE: Mounting database on port 33389
        VERBOSE: In order to dismount the database, close dsamain and then run "Dismount-ActiveDirectorySnapshot
 
        Mount the latest Active Directory snapshot.
    #>


    [CmdletBinding(SupportsShouldProcess=$true, 
                  ConfirmImpact='Medium')]
    Param
    (
        # The identity of the snapshot to mount
        [Parameter(Mandatory=$true, 
                   ValueFromPipeline=$true,
                   ValueFromPipelineByPropertyName=$true, 
                   ValueFromRemainingArguments=$false, 
                   Position=0)]
        [ValidateNotNull()]
        [string]
        $Identity,

        # The port to use in order to query the mounted database
        [Parameter(Mandatory=$true, 
                   Position=1)]
        [ValidateNotNull()]
        [ValidateRange(1025,65535)]
        [int]
        $Port
        
    )

    Begin {}

    Process
    {
        if($PSCmdlet.ShouldProcess($Identity, "Mount Active Directory snapshot"))
        {
            # Mount the snapshot
            $pinfo = New-Object System.Diagnostics.ProcessStartInfo
            $pinfo.FileName = "ntdsutil"
            $pinfo.RedirectStandardError = $true
            $pinfo.RedirectStandardOutput = $true
            $pinfo.RedirectStandardInput = $true
            $pinfo.UseShellExecute = $false
            $pinfo.CreateNoWindow = $true
    
            $p = New-Object System.Diagnostics.Process
            $p.StartInfo = $pinfo
            $p.Start() | Out-Null

            $p.StandardInput.WriteLine("Activate Instance NTDS")
            $p.StandardInput.WriteLine("snapshot")
            $p.StandardOutput.DiscardBufferedData()
            $p.StandardInput.WriteLine("mount $Identity")
            $p.StandardInput.WriteLine("quit")
            $p.StandardInput.WriteLine("quit")
            $p.WaitForExit()


            $stdout = $p.StandardOutput.ReadToEnd()
            $stderr = $p.StandardError.ReadToEnd()
            
            if($p.ExitCode -ne 0)
            {
                Write-Error $stderr
                return $null
            }
            else
            {
                # Get the snapshot mount directory
                $mountPoint = (Get-ActiveDirectorySnapshot -Identity $Identity).MountPoint

                # Add the path to the database file
                $mountPoint += (Get-Item -Path "HKLM:\SYSTEM\CurrentcontrolSet\Services\NTDS\Parameters").GetValue("DSA Database File").SubString(3)
            }

            if($mountPoint)
            { 
                Write-Verbose "Loading database: $mountPoint"

                # Create a background job and start dsamain
                Write-Verbose ("Mounting database on port $Port")
                
                # Start DSAMAIN
                $DSAMAIN = Start-Process -FilePath dsamain.exe -ArgumentList "-dbpath $mountPoint -ldapport $Port" -PassThru                
                
                Write-Verbose ('In order to dismount the database, close dsamain and then run "Dismount-ActiveDirectorySnapshot')
            }
            else
            {
                Write-Error "Could not mount the database."
            }
        }
    }

    End {}
}
#endregion

#region Dismount-ActiveDirectorySnapshot
function Dismount-ActiveDirectorySnapshot
{
    <#
    .Synopsis
       Dismount an Active Directory snapshot.
    .DESCRIPTION
       Dismount and Active Directory snapshot.
    .EXAMPLE
        PS C:\> Dismount-ActiveDirectorySnapshot -Identity "{CAE74093-6422-42D5-AB1B-988C418E1560}" -Verbose
        VERBOSE: Performing the operation "Dismount Active Directory snapshot" on target "{CAE74093-6422-42D5-AB1B-988C418E1560}".
 
        Dismount the Active Directory snapshot with id {CAE74093-6422-42D5-AB1B-988C418E1560}
    .EXAMPLE
        PS C:\> Get-ActiveDirectorySnapshot | ? mounted -eq $true | Dismount-ActiveDirectorySnapshot -Verbose
        VERBOSE: Performing the operation "Dismount Active Directory snapshot" on target "{CAE74093-6422-42D5-AB1B-988C418E1560}".
     
        Dismount all currently mounted Active Directory snapshots.
    #>


    [CmdletBinding(SupportsShouldProcess=$true, 
                  ConfirmImpact='Medium')]
    Param
    (
        # The identity of the snapshot to mount
        [Parameter(Mandatory=$true, 
                   ValueFromPipeline=$true,
                   ValueFromPipelineByPropertyName=$true, 
                   ValueFromRemainingArguments=$false, 
                   Position=0)]
        [ValidateNotNull()]
        [string]
        $Identity
    )

    Begin {}

    Process
    {
        if($PSCmdlet.ShouldProcess($Identity, "Dismount Active Directory snapshot"))
        {
            # Dismount the snapshot
            $pinfo = New-Object System.Diagnostics.ProcessStartInfo
            $pinfo.FileName = "ntdsutil"
            $pinfo.RedirectStandardError = $true
            $pinfo.RedirectStandardOutput = $true
            $pinfo.RedirectStandardInput = $true
            $pinfo.UseShellExecute = $false
            $pinfo.CreateNoWindow = $true
    
            $p = New-Object System.Diagnostics.Process
            $p.StartInfo = $pinfo
            $p.Start() | Out-Null

            $p.StandardInput.WriteLine("Activate Instance NTDS")
            $p.StandardInput.WriteLine("snapshot")
            $p.StandardOutput.DiscardBufferedData()
            $p.StandardInput.WriteLine("unmount $Identity")
            $p.StandardInput.WriteLine("quit")
            $p.StandardInput.WriteLine("quit")
            $p.WaitForExit()

            $stdout = $p.StandardOutput.ReadToEnd()
            $stderr = $p.StandardError.ReadToEnd()
            
            if($p.ExitCode -ne 0)
            {
                Write-Error $stderr
                return $null
            }
            else
            {
            }
        }
    }

    End {}
}
#endregion

#region Compare-ActiveDirectorySnapshotObject
function Compare-ActiveDirectorySnapshotObject
{
    <#
    .Synopsis
       Short description
    .DESCRIPTION
       Long description
    .EXAMPLE
        PS C:\> $guid = (Get-ADUser cpolydorou).ObjectGUID
        PS C:\> Compare-ActiveDirectorySnapshotObject -ObjectGUID $guid -ProductionServer localhost -SnapshotServer localhost:33389 -Attributes SamAccountName,GivenName,SN
 
        Attribute ProductionValue SnapshotValue Status
        --------- --------------- ------------- ------
        DistinguishedName CN=Christos Polydorou,OU=U... CN=Christos Polydorou,OU=U... Equal
        GivenName Christos Christos Equal
        Name Christos Polydorou Christos Polydorou Equal
        ObjectClass user user Equal
        ObjectGUID 241a6ed9-832e-458b-ab77-c8... 241a6ed9-832e-458b-ab77-c8... Equal
        SamAccountName cpolydorou cpolydorou Equal
        SN Polydorou 2 Polydorou Different
                 
        Compare the values of SamAccountName, GivenName and SN for the user cpolydorou using the object's ObjectGUID
    #>


    [CmdletBinding()]

    Param
    (
        # The identity of the object to compare
        [Parameter(Mandatory=$true, 
                   ValueFromPipeline=$true,
                   ValueFromPipelineByPropertyName=$true, 
                   ValueFromRemainingArguments=$false, 
                   Position=0)]
        [ValidateNotNullOrEmpty()]
        [string[]]
        $ObjectGUID,

        # The production Domain Controller
        [Parameter(Mandatory=$true, 
                   Position=1)]
        [ValidateNotNullOrEmpty()]
        [string]
        $ProductionServer,

        # The snapshot Domain Controller
        [Parameter(Mandatory=$true, 
                   Position=2)]
        [ValidateNotNullOrEmpty()]
        [string]
        $SnapshotServer,

        # The attributes to load
        [Parameter(Mandatory=$false, 
                   Position=3)]
        [string[]]
        $Attributes = "*"

    )

    Begin
    {
        # Load the ActiveDirectory module
        try
        {
            Import-Module ActiveDirectory -ErrorAction Stop
        }
        catch
        {
            Throw "Could not load the ActiveDirectory module."
        }
    }
    Process
    {
        foreach($o in $ObjectGUID)
        {
            # Get the object from the production DC
            $productionObject = Get-ADObject -Filter {objectguid -eq $o} -Properties $Attributes -Server $ProductionServer

            # Check if the object exists
            if( -not $productionObject)
            {
                Write-Error "Could not find an object with GUID $o in production server."
            }

            # Get the object from the snapshot
            $snapshotObject = Get-ADObject -Filter {objectguid -eq $o} -Properties $Attributes -Server $SnapshotServer

            # Check if the object exists
            if(-not $snapshotObject)
            {
                Write-Error "Could not find an object with GUID $o in snapshot server."
            }

            Compare-ActiveDirectoryObject -ReferenceObject $productionObject -DifferenceObject $snapshotObject |
                Select-Object -Property @{Name = "Attribute"; Expression = {$_.PropertyName}}, `
                                        @{Name = "ProductionValue"; Expression = {$_.ReferenceValue}}, `
                                        @{Name = "SnapshotValue"; Expression = {$_.DifferenceValue}}, `
                                        Status
        }        
    }
    End {}
}
#endregion

#region Restore-ActiveDirectoryAttribute
function Restore-ActiveDirectoryAttribute
{
    <#
    .Synopsis
       Restore Active Directory attributes.
    .DESCRIPTION
       Restore Active Directory object attributes using an Active Directory snapshot
    .EXAMPLE
        PS C:\Windows\system32> $guid = (Get-ADUser cpolydorou).ObjectGUID
 
        PS C:\Windows\system32> Restore-ActiveDirectoryAttribute -ObjectGUID $guid -ProductionServer localhost -SnapshotServer localhost:33389 -Attribute sn,givenname -Verbose
        VERBOSE: Performing the operation "Restore attribute sn" on target "CN=Christos Polydorou,OU=Users,OU=LAB,DC=LAB,DC=local".
        VERBOSE: Performing the operation "Restore attribute givenname" on target "CN=Christos Polydorou,OU=Users,OU=LAB,DC=LAB,DC=local".
 
        Restore the sn and givenname attributes for user "cpolydorou"
    #>


    [CmdletBinding(SupportsShouldProcess=$true, 
                  PositionalBinding=$false,
                  ConfirmImpact='High')]
    Param
    (
        # The ObjectGUID of the Active Directory object
        [Parameter(Mandatory=$true, 
                   ValueFromPipeline=$true,
                   ValueFromPipelineByPropertyName=$true, 
                   ValueFromRemainingArguments=$false, 
                   Position=0)]
        [ValidateNotNullOrEmpty()]
        [string]
        $ObjectGUID,

        # The attribute to restore
        [Parameter(Mandatory=$true, 
                   Position=1)]
        [ValidateNotNullOrEmpty()]
        [string[]]
        $Attribute,

        # The production server
        [Parameter(Mandatory=$true, 
                   Position=2)]
        [ValidateNotNullOrEmpty()]
        [string]
        $ProductionServer,

        # The snapshot server
        [Parameter(Mandatory=$true, 
                   Position=3)]
        [ValidateNotNullOrEmpty()]
        [string]
        $SnapshotServer
    )

    Begin
    {
        # Import the ActiveDirectory module
        try
        {
            Import-Module ActiveDirectory -ErrorAction Stop -Verbose:$false
        }
        catch
        {
            Throw "Could not load the ActiveDirectory module."
        }
    }

    Process
    {
        foreach($o in $ObjectGUID)
        {
            # Get the object from the production DC
            $productionObject = Get-ADObject -Filter {objectguid -eq $o} -Properties $Attribute -Server $ProductionServer

            # Check if the object exists
            if( -not $productionObject)
            {
                Write-Error "Could not find an object with GUID $o in production server."
                continue
            }

            # Get the object from the snapshot
            $snapshotObject = Get-ADObject -Filter {objectguid -eq $o} -Properties $Attribute -Server $SnapshotServer

            # Check if the object exists
            if(-not $snapshotObject)
            {
                Write-Error "Could not find an object with GUID $o in snapshot server."
                continue
            }

            # Restore the attributes
            foreach($a in $Attribute)
            {
                # TODO: Check if the attribute exists
                if($productionObject.PropertyNames -notcontains $a)
                {
                    Write-Error "Attribute $a could not be found."
                }

                # Set the value on the production
                if ($pscmdlet.ShouldProcess($productionObject.DistinguishedName, "Restore attribute $a"))
                {
                    # Get the value from the snapshot object
                    $value  = $snapshotObject | % $a

                    # Form the hashtable
                    $table = @{ "$a" = "$value"}
                    Set-ADObject -Identity $o `
                                 -Server $ProductionServer `
                                 -Confirm:$false `
                                 -replace $table                    
                }
            }
        }
    }

    End {}
}
#endregion

#region Exports
Export-ModuleMember -Function Get-ActiveDirectorySnapshot
Export-ModuleMember -Function New-ActiveDirectorySnapshot
Export-ModuleMember -Function Remove-ActiveDirectorySnapshot
Export-ModuleMember -Function Mount-ActiveDirectorySnapshot
Export-ModuleMember -Function Dismount-ActiveDirectorySnapshot
Export-ModuleMember -Function Compare-ActiveDirectorySnapshotObject
Export-ModuleMember -Function Restore-ActiveDirectoryAttribute
#endregion