DSCResources/DSC_MountImage/DSC_MountImage.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
$modulePath = Join-Path -Path (Split-Path -Path (Split-Path -Path $PSScriptRoot -Parent) -Parent) -ChildPath 'Modules'

# Import the Storage Common Module.
Import-Module -Name (Join-Path -Path $modulePath `
        -ChildPath (Join-Path -Path 'StorageDsc.Common' `
            -ChildPath 'StorageDsc.Common.psm1'))

Import-Module -Name (Join-Path -Path $modulePath -ChildPath 'DscResource.Common')

# Import Localization Strings.
$script:localizedData = Get-LocalizedData -DefaultUICulture 'en-US'

<#
    .SYNOPSIS
        Returns the current mount state of the VHD or ISO file.
 
    .PARAMETER ImagePath
        Specifies the path of the VHD or ISO file.
#>

function Get-TargetResource
{
    [CmdletBinding()]
    [OutputType([System.Collections.Hashtable])]
    param
    (
        [Parameter(Mandatory = $true)]
        [System.String]
        $ImagePath
    )

    Write-Verbose -Message ( @(
            "$($MyInvocation.MyCommand): "
            $($script:localizedData.GettingMountedImageMessage `
                -f $ImagePath)
        ) -join '' )

    $diskImage = Get-DiskImage -ImagePath $ImagePath

    if ($diskImage.Attached)
    {
        $returnValue = @{
            ImagePath   = $ImagePath
            DriveLetter = ''
            StorageType = [Microsoft.PowerShell.Cmdletization.GeneratedTypes.DiskImage.StorageType] $diskImage.StorageType
            Access      = 'ReadOnly'
            Ensure      = 'Present'
        }

        # Determine the Disk Image Access mode
        if ($diskImage.StorageType `
            -eq [Microsoft.PowerShell.Cmdletization.GeneratedTypes.DiskImage.StorageType]::ISO)
        {
            # Get the Drive Letter the ISO is mounted as
            $volume = $diskImage | Get-Volume
            $returnValue.Driveletter = $volume.DriveLetter
        }
        else
        {
            # Look up the disk and find out if it is readwrite.
            $disk = Get-Disk -Number $diskImage.Number
            if (-not $disk.IsReadOnly)
            {
                $returnValue.Access = 'ReadWrite'
            } # if

            # Find the first 'Basic' partition
            $partitions = $disk | Get-Partition
            $partition = $partitions | Where-Object -Property Type -EQ 'Basic'

            # Find the first volume in the partition and get the mounted Drive Letter
            $volumes = $partition | Get-Volume
            $volume = $volumes | Select-Object -First 1

            $returnValue.Driveletter = $volume.DriveLetter
        } # if
    }
    else
    {
        $returnValue = @{
            ImagePath   = $ImagePath
            Ensure      = 'Absent'
        }
    } # if

    $returnValue
} # Get-TargetResource

<#
    .SYNOPSIS
        Mounts or dismounts the ISO or VHD.
 
    .PARAMETER ImagePath
        Specifies the path of the VHD or ISO file.
 
    .PARAMETER DriveLetter
        Specifies the drive letter to mount this VHD or ISO to.
 
    .PARAMETER StorageType
        Specifies the storage type of a file. If the StorageType parameter is not specified, then the storage type is determined by file extension.
 
    .PARAMETER Access
        Allows a VHD file to be mounted in read-only or read-write mode. ISO files are mounted in read-only mode regardless of what parameter value you provide.
 
    .PARAMETER Ensure
        Determines whether the setting should be applied or removed.
#>

function Set-TargetResource
{
    # Should process is called in a helper functions but not directly in Set-TargetResource
    [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSShouldProcess', '')]
    [CmdletBinding(SupportsShouldProcess = $true)]
    param
    (
        [Parameter(Mandatory = $true)]
        [System.String]
        $ImagePath,

        [Parameter()]
        [System.String]
        $DriveLetter,

        [Parameter()]
        [ValidateSet('ISO','VHD','VHDx','VHDSet')]
        [System.String]
        $StorageType,

        [Parameter()]
        [ValidateSet('ReadOnly','ReadWrite')]
        [System.String]
        $Access,

        [Parameter()]
        [ValidateSet('Present','Absent')]
        [System.String]
        $Ensure = 'Present'
    )

    Write-Verbose -Message ( @(
            "$($MyInvocation.MyCommand): "
            $($script:localizedData.SettingMountedImageMessage `
                -f $ImagePath)
        ) -join '' )

    # Check the parameter combo passed is valid, and throw if not.
    $null = Test-ParameterValid @PSBoundParameters

    # Get the current mount state of this disk image
    $currentState = Get-TargetResource -ImagePath $ImagePath

    # Remove Ensure from PSBoundParameters so it can be splatted
    $null = $PSBoundParameters.Remove('Ensure')

    if ($Ensure -eq 'Present')
    {
        # Get the normalized DriveLetter (colon removed)
        $normalizedDriveLetter = Assert-DriveLetterValid -DriveLetter $DriveLetter

        # The Disk Image should be mounted
        $needsMount = $false
        if ($currentState.Ensure -eq 'Absent')
        {
            $needsMount = $true
        }
        else
        {
            if ($currentState.DriveLetter -ne $normalizedDriveLetter)
            {
                # The disk image is mounted to the wrong DriveLetter -remount disk
                Write-Verbose -Message ( @(
                        "$($MyInvocation.MyCommand): "
                        $($script:localizedData.DismountingImageMessage `
                            -f $ImagePath,$currentState.DriveLetter)
                    ) -join '' )

                Dismount-DiskImage -ImagePath $ImagePath
                $needsMount = $true
            } # if
        } # if

        if ($currentState.StorageType -ne 'ISO')
        {
            if ($PSBoundParameters.ContainsKey('Access'))
            {
                # For VHD/VHDx/VHDSet disks check the access mode
                if ($currentState.Access -ne $Access)
                {
                    # The access mode is wrong -remount disk
                    Write-Verbose -Message ( @(
                            "$($MyInvocation.MyCommand): "
                            $($script:localizedData.DismountingImageMessage `
                                -f $ImagePath,$currentState.DriveLetter)
                        ) -join '' )

                    Dismount-DiskImage -ImagePath $ImagePath
                    $needsMount = $true
                } # if
            } # if
        } # if

        if ($needsMount)
        {
        Write-Verbose -Message ( @(
                "$($MyInvocation.MyCommand): "
                $($script:localizedData.MountingImageMessage `
                    -f $ImagePath,$normalizedDriveLetter)
            ) -join '' )

            Mount-DiskImageToLetter @PSBoundParameters
        } # if
    }
    else
    {
        # The Disk Image should not be mounted
        if ($currentState.Ensure -eq 'Present')
        {
            # It is mounted so dismount it
            Write-Verbose -Message ( @(
                    "$($MyInvocation.MyCommand): "
                    $($script:localizedData.DismountingImageMessage `
                        -f $ImagePath,$currentState.DriveLetter)
                ) -join '' )

            Dismount-DiskImage -ImagePath $ImagePath
        }
    } # if
} # Set-TargetResource

<#
    .SYNOPSIS
        Tests if the ISO or VHD file mount is in the correct state.
 
    .PARAMETER ImagePath
        Specifies the path of the VHD or ISO file.
 
    .PARAMETER DriveLetter
        Specifies the drive letter to mount this VHD or ISO to.
 
    .PARAMETER StorageType
        Specifies the storage type of a file. If the StorageType parameter is not
        specified, then the storage type is determined by file extension.
 
    .PARAMETER Access
        Allows a VHD file to be mounted in read-only or read-write mode. ISO files
        are mounted in read-only mode regardless of what parameter value you provide.
 
    .PARAMETER Ensure
        Determines whether the setting should be applied or removed.
#>

function Test-TargetResource
{
    [CmdletBinding()]
    [OutputType([System.Boolean])]
    param
    (
        [Parameter(Mandatory = $true)]
        [System.String]
        $ImagePath,

        [Parameter()]
        [System.String]
        $DriveLetter,

        [Parameter()]
        [ValidateSet('ISO','VHD','VHDx','VHDSet')]
        [System.String]
        $StorageType,

        [Parameter()]
        [ValidateSet('ReadOnly','ReadWrite')]
        [System.String]
        $Access,

        [Parameter()]
        [ValidateSet('Present','Absent')]
        [System.String]
        $Ensure = 'Present'
    )

    Write-Verbose -Message ( @(
            "$($MyInvocation.MyCommand): "
            $($script:localizedData.TestingMountedImageMessage `
                -f $DriveLetter)
        ) -join '' )

    # Check the parameter combo passed is valid, and throw if not.
    $null = Test-ParameterValid @PSBoundParameters

    # Get the current mount state of this disk image
    $currentState = Get-TargetResource -ImagePath $ImagePath

    if ($Ensure -eq 'Present')
    {
        # Get the normalized DriveLetter (colon removed)
        $normalizedDriveLetter = Assert-DriveLetterValid -DriveLetter $DriveLetter

        # The Disk Image should be mounted
        if ($currentState.Ensure -eq 'Absent')
        {
            # The disk image isn't mounted
            Write-Verbose -Message ( @(
                    "$($MyInvocation.MyCommand): "
                    $($script:localizedData.ImageIsNotMountedButShouldBeMessage `
                        -f $ImagePath,$normalizedDriveLetter)
                ) -join '' )
            return $false
        } # if

        if ($currentState.DriveLetter -ne $normalizedDriveLetter)
        {
            # The disk image is mounted to the wrong DriveLetter
            Write-Verbose -Message ( @(
                    "$($MyInvocation.MyCommand): "
                    $($script:localizedData.ImageIsMountedToTheWrongDriveLetterMessage `
                        -f $ImagePath,$currentState.DriveLetter,$normalizedDriveLetter)
                ) -join '' )
            return $false
        } # if

        if ($currentState.StorageType -ne 'ISO')
        {
            if ($PSBoundParameters.ContainsKey('Access'))
            {
                # For VHD/VHDx/VHDSet disks check the access mode
                if ($currentState.Access -ne $Access)
                {
                    Write-Verbose -Message ( @(
                            "$($MyInvocation.MyCommand): "
                            $($script:localizedData.VHDAccessModeMismatchMessage `
                                -f $ImagePath,$normalizedDriveLetter,$currentState.Access,$Access)
                        ) -join '' )
                    return $false
                } # if
            } # if
        } # if

        # The Disk Image is mounted to the expected Drive - nothing to change.
        Write-Verbose -Message ( @(
                "$($MyInvocation.MyCommand): "
                $($script:localizedData.ImageIsMountedAndShouldBeMessage `
                    -f $ImagePath,$normalizedDriveLetter)
            ) -join '' )
    }
    else
    {
        # The Disk Image should not be mounted
        if ($currentState.Ensure -eq 'Present')
        {
            # The disk image is mounted
            Write-Verbose -Message ( @(
                    "$($MyInvocation.MyCommand): "
                    $($script:localizedData.ImageIsMountedButShouldNotBeMessage `
                        -f $ImagePath,$currentState.DriveLetter)
                ) -join '' )
            return $false
        } # if

        # The image is not mounted and should not be
        Write-Verbose -Message ( @(
                "$($MyInvocation.MyCommand): "
                $($script:localizedData.ImageIsNotMountedAndShouldNotBeMessage `
                    -f $ImagePath)
            ) -join '' )
    } # if

    # No changes are needed
    return $true
} # Test-TargetResource

<#
    .SYNOPSIS
        Validates that the parameters passed are valid. If the parameter combination
        is invalid then an exception will be thrown. Also validates the DriveLetter
        value that is passed is valid.
 
    .PARAMETER ImagePath
        Specifies the path of the VHD or ISO file.
 
    .PARAMETER DriveLetter
        Specifies the drive letter to mount this VHD or ISO to.
 
    .PARAMETER StorageType
        Specifies the storage type of a file. If the StorageType parameter is not
        specified, then the storage type is determined by file extension.
 
    .PARAMETER Access
        Allows a VHD file to be mounted in read-only or read-write mode. ISO files
        are mounted in read-only mode regardless of what parameter value you provide.
 
    .PARAMETER Ensure
        Determines whether the setting should be applied or removed.
 
    .OUTPUTS
        If ensure is present then returns a normalized array of Drive Letters.
#>

function Test-ParameterValid
{
    [CmdletBinding()]
    [OutputType([String[]])]
    param
    (
        [Parameter(Mandatory = $true)]
        [System.String]
        $ImagePath,

        [Parameter()]
        [System.String]
        $DriveLetter,

        [Parameter()]
        [ValidateSet('ISO','VHD','VHDx','VHDSet')]
        [System.String]
        $StorageType,

        [Parameter()]
        [ValidateSet('ReadOnly','ReadWrite')]
        [System.String]
        $Access,

        [Parameter()]
        [ValidateSet('Present','Absent')]
        [System.String]
        $Ensure = 'Present'
    )

    if ($Ensure -eq 'Absent')
    {
        if ($PSBoundParameters.ContainsKey('DriveLetter'))
        {
            # The DriveLetter should not be set if Ensure is Absent
            New-InvalidOperationException `
                -Message ($script:localizedData.InvalidParameterSpecifiedError -f `
                    'Absent','DriveLetter')
        } # if

        if ($PSBoundParameters.ContainsKey('StorageType'))
        {
            # The StorageType should not be set if Ensure is Absent
            New-InvalidOperationException `
                -Message ($script:localizedData.InvalidParameterSpecifiedError -f `
                    'Absent','StorageType')
        } # if

        if ($PSBoundParameters.ContainsKey('Access'))
        {
            # The Access should not be set if Ensure is Absent
            New-InvalidOperationException `
                -Message ($script:localizedData.InvalidParameterSpecifiedError -f `
                    'Absent','Access')
        } # if
    }
    else
    {
        if (-not (Test-Path -Path $ImagePath))
        {
            # The file specified by ImagePath should be found
            New-InvalidOperationException `
                -Message ($script:localizedData.DiskImageFileNotFoundError -f `
                    $ImagePath)
        } # if

        if ($PSBoundParameters.ContainsKey('DriveLetter'))
        {
            # Test the Drive Letter to ensure it is valid
            $normalizedDriveLetter = Assert-DriveLetterValid -DriveLetter $DriveLetter
        }
        else
        {
            # Drive letter is not specified but Ensure is present.
            New-InvalidOperationException `
                -Message ($script:localizedData.InvalidParameterNotSpecifiedError -f `
                    'Present','DriveLetter')
        } # if
    } # if
} # Test-ParameterValid

<#
    .SYNOPSIS
        Mounts a Disk Image to a specific Drive Letter.
 
    .PARAMETER ImagePath
        Specifies the path of the VHD or ISO file.
 
    .PARAMETER DriveLetter
        Specifies the drive letter to mount this VHD or ISO to.
 
    .PARAMETER StorageType
        Specifies the storage type of a file. If the StorageType parameter is not
        specified, then the storage type is determined by file extension.
 
    .PARAMETER Access
        Allows a VHD file to be mounted in read-only or read-write mode. ISO files
        are mounted in read-only mode regardless of what parameter value you provide.
#>

function Mount-DiskImageToLetter
{
    [CmdletBinding()]
    [OutputType([String[]])]
    param
    (
        [Parameter(Mandatory = $true)]
        [System.String]
        $ImagePath,

        [Parameter()]
        [System.String]
        $DriveLetter,

        [Parameter()]
        [ValidateSet('ISO','VHD','VHDx','VHDSet')]
        [System.String]
        $StorageType,

        [Parameter()]
        [ValidateSet('ReadOnly','ReadWrite')]
        [System.String]
        $Access
    )

    # Get the normalized DriveLetter (colon removed)
    $normalizedDriveLetter = Assert-DriveLetterValid -DriveLetter $DriveLetter

    # Mount the Diskimage
    $mountParams = @{
        ImagePath = $ImagePath
    }

    if ($PSBoundParameters.ContainsKey('Access'))
    {
        $mountParams += @{
            Access = $Access
        }
    }  # if
    $null = Mount-DiskImage @mountParams

    # Get the DiskImage object
    $diskImage = Get-DiskImage -ImagePath $ImagePath

    # Determine the Storage Type expected
    if (-not $PSBoundParameters.ContainsKey('StorageType'))
    {
        $StorageType = [Microsoft.PowerShell.Cmdletization.GeneratedTypes.DiskImage.StorageType] $diskImage.StorageType
    } # if

    # Different StorageType images require different methods of getting the Volume object.
    if ($StorageType -eq [Microsoft.PowerShell.Cmdletization.GeneratedTypes.DiskImage.StorageType]::ISO)
    {
        # This is a ISO diskimage
        $volume = $diskImage | Get-Volume
    }
    else
    {
        # This is a VHD/VHDx/VHDSet diskimage
        $disk = Get-Disk -Number $diskImage.Number

        # Find the first 'Basic' partition to mount
        $partitions = $disk | Get-Partition
        $partition = $partitions | Where-Object -Property Type -EQ 'Basic'

        # Find the first volume in the partition and get the mounted Drive Letter
        $volumes = $partition | Get-Volume
        $volume = $volumes | Select-Object -First 1
    } # if

    $currentDriveLetter = $volume.DriveLetter

    # Verify that the drive letter assigned to the drive is the one needed.
    if ($currentDriveLetter -ne $normalizedDriveLetter)
    {
        Write-Verbose -Message ( @(
                "$($MyInvocation.MyCommand): "
                $($script:localizedData.ChangingImageDriveLetterMessage `
                    -f $ImagePath,$currentDriveLetter,$normalizedDriveLetter)
            ) -join '' )

        <#
            Use CIM to change the DriveLetter.
            The Win32_Volume must be looked up using the ObjectId found in the Volume object
            ObjectId is more verbose than DeviceId in Windows 10 Anniversary Edition, look for
            DeviceId in the ObjectId string to match volumes.
        #>

        $cimVolume = Get-CimInstance -ClassName Win32_Volume |
            Where-Object -FilterScript {
                $volume.ObjectId.IndexOf($_.DeviceId) -ne -1
            }

        Set-CimInstance `
            -InputObject $cimVolume `
            -Property @{
                DriveLetter = "$($normalizedDriveLetter):"
            }
    } # if
} # Mount-DiskImageToLetter

Export-ModuleMember -Function *-TargetResource