VHDX.psm1
$script:ModuleRoot = $PSScriptRoot $script:ModuleVersion = (Import-PSFPowerShellDataFile -Path "$($script:ModuleRoot)\VHDX.psd1").ModuleVersion # Detect whether at some level dotsourcing was enforced $script:doDotSource = Get-PSFConfigValue -FullName VHDX.Import.DoDotSource -Fallback $false if ($VHDX_dotsourcemodule) { $script:doDotSource = $true } <# Note on Resolve-Path: All paths are sent through Resolve-Path/Resolve-PSFPath in order to convert them to the correct path separator. This allows ignoring path separators throughout the import sequence, which could otherwise cause trouble depending on OS. Resolve-Path can only be used for paths that already exist, Resolve-PSFPath can accept that the last leaf my not exist. This is important when testing for paths. #> # Detect whether at some level loading individual module files, rather than the compiled module was enforced $importIndividualFiles = Get-PSFConfigValue -FullName VHDX.Import.IndividualFiles -Fallback $false if ($VHDX_importIndividualFiles) { $importIndividualFiles = $true } if (Test-Path (Resolve-PSFPath -Path "$($script:ModuleRoot)\..\.git" -SingleItem -NewChild)) { $importIndividualFiles = $true } if ("<was compiled>" -eq '<was not compiled>') { $importIndividualFiles = $true } function Import-ModuleFile { <# .SYNOPSIS Loads files into the module on module import. .DESCRIPTION This helper function is used during module initialization. It should always be dotsourced itself, in order to proper function. This provides a central location to react to files being imported, if later desired .PARAMETER Path The path to the file to load .EXAMPLE PS C:\> . Import-ModuleFile -File $function.FullName Imports the file stored in $function according to import policy #> [CmdletBinding()] Param ( [string] $Path ) $resolvedPath = $ExecutionContext.SessionState.Path.GetResolvedPSPathFromPSPath($Path).ProviderPath if ($doDotSource) { . $resolvedPath } else { $ExecutionContext.InvokeCommand.InvokeScript($false, ([scriptblock]::Create([io.file]::ReadAllText($resolvedPath))), $null, $null) } } #region Load individual files if ($importIndividualFiles) { # Execute Preimport actions foreach ($path in (& "$ModuleRoot\internal\scripts\preimport.ps1")) { . Import-ModuleFile -Path $path } # Import all internal functions foreach ($function in (Get-ChildItem "$ModuleRoot\internal\functions" -Filter "*.ps1" -Recurse -ErrorAction Ignore)) { . Import-ModuleFile -Path $function.FullName } # Import all public functions foreach ($function in (Get-ChildItem "$ModuleRoot\functions" -Filter "*.ps1" -Recurse -ErrorAction Ignore)) { . Import-ModuleFile -Path $function.FullName } # Execute Postimport actions foreach ($path in (& "$ModuleRoot\internal\scripts\postimport.ps1")) { . Import-ModuleFile -Path $path } # End it here, do not load compiled code below return } #endregion Load individual files #region Load compiled code <# This file loads the strings documents from the respective language folders. This allows localizing messages and errors. Load psd1 language files for each language you wish to support. Partial translations are acceptable - when missing a current language message, it will fallback to English or another available language. #> Import-PSFLocalizedString -Path "$($script:ModuleRoot)\en-us\*.psd1" -Module 'VHDX' -Language 'en-US' function Assert-Elevation { <# .SYNOPSIS Asserts the current console is running "As Administrator" .DESCRIPTION Asserts the current console is running "As Administrator" .PARAMETER Cmdlet The $PSCmdlet variable of the caller, enabling errors to look as generated from that, rather than this internal helper. .EXAMPLE PS C:\> Assert-Elevation -Cmdlet $PSCmdlet Asserts the current console is running "As Administrator" #> [CmdletBinding()] param ( [Parameter(Mandatory = $true)] $Cmdlet ) process { if (Test-PSFPowerShell -Elevated) { return } $exception = [System.InvalidOperationException]::new('Insufficient privileges, this command requires elevation and must be run "As Administrator"') $record = [System.Management.Automation.ErrorRecord]::new($exception, 'NotElevated', [System.Management.Automation.ErrorCategory]::SecurityError, $null) $Cmdlet.ThrowTerminatingError($record) } } function Add-VhdxContent { <# .SYNOPSIS Adds files and folders to a target VHDX file. .DESCRIPTION Adds files and folders to a target VHDX file. If the VHDX hasn't been mounted yet, it will be mounted before adding content and dismounted once done. Note: Only supports single-volume VHDX files. .PARAMETER Path Path to the VHDX file. .PARAMETER SubPath Relative path _within_ the volume of the VHDX file, where to add the new files & folders. Defaults to the volume root. .PARAMETER Content Files and folders to add to the disk. .PARAMETER EnableException This parameters disables user-friendly warnings and enables the throwing of exceptions. This is less user friendly, but allows catching exceptions in calling scripts. .EXAMPLE PS C:\> Get-ChildItem C:\Data | Add-VhdxContent -Path 'c:\disks\data.vhdx' Adds everything under C:\Data to the root level of the volume in the disk 'c:\disks\data.vhdx' .EXAMPLE PS C:\> Get-ChildItem C:\Documents | Add-VhdxContent -Path 'c:\disks\data.vhdx' -SubPath "$env:COMPUTERNAME\documents" Adds everything under C:\Documents to the subfolder "$env:COMPUTERNAME\documents" of the volume in the disk 'c:\disks\data.vhdx' #> [CmdletBinding()] param ( [Parameter(Mandatory = $true)] [PsfValidateScript('PSFramework.Validate.FSPath.File', ErrorString = 'PSFramework.Validate.FSPath.File')] [string] $Path, [string] $SubPath, [Parameter(Mandatory = $true, ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true)] [Alias('FullName')] [string[]] $Content, [switch] $EnableException ) begin { Assert-Elevation -Cmdlet $PSCmdlet $resolvedPath = Resolve-PSFPath -Path $Path -Provider FileSystem -SingleItem $wasMounted = $false $disk = Get-Disk | Where-Object Location -EQ $resolvedPath if (-not $disk) { Mount-Vhdx -Path $resolvedPath $disk = Get-Disk | Where-Object Location -EQ $resolvedPath if ($disk) { $wasMounted = $true } } if (-not $disk) { Stop-PSFFunction -String 'Add-VhdxContent.Mount.Failed' -StringValues $resolvedPath -EnableException $EnableException -Cmdlet $PSCmdlet -Target $resolvedPath return } $volume = $disk | Get-Partition | Get-Volume if (@($volume).Count -gt 1) { Stop-PSFFunction -String 'Add-VhdxContent.Volumes.Multiple.Error' -StringValues $resolvedPath -EnableException $EnableException -Cmdlet $PSCmdlet -Target $resolvedPath return } $rootPath = '{0}:\' -f $volume.DriveLetter if ($SubPath) { $rootPath = Join-Path -Path $rootPath -ChildPath $SubPath } } process { if (Test-PSFFunctionInterrupt) { return } foreach ($item in $Content) { Write-PSFMessage -String 'Add-VhdxContent.Adding.Item' -StringValues $item -Target $resolvedPath Copy-Item -Path $item -Destination $rootPath -Recurse -Force } } end { if ($wasMounted) { Dismount-Vhdx -Path $resolvedPath } } } function Dismount-Vhdx { <# .SYNOPSIS Dismounts an already mounted VHDX file. .DESCRIPTION Dismounts an already mounted VHDX file. Use 'Mount-Vhdx' to mount one. .PARAMETER Path Path to the VHDX file to dismount. .PARAMETER EnableException This parameters disables user-friendly warnings and enables the throwing of exceptions. This is less user friendly, but allows catching exceptions in calling scripts. .EXAMPLE PS C:\> Dismount-Vhdx -Path 'c:\disks\profile.vhdx' Dismounts the file 'c:\disks\profile.vhdx' #> [CmdletBinding()] param ( [Parameter(Mandatory = $true, ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true)] [PsfValidateScript('PSFramework.Validate.FSPath.File', ErrorString = 'PSFramework.Validate.FSPath.File')] [Alias('FullName')] [string[]] $Path, [switch] $EnableException ) begin { Assert-Elevation -Cmdlet $PSCmdlet } process { foreach ($filePath in $Path) { Write-PSFMessage -String 'Dismount-Vhdx.Unmounting' -StringValues $filePath $resolvedPath = Resolve-PSFPath -Path $filePath -Provider FileSystem -SingleItem $result = Invoke-Diskpart -ArgumentList @( ('select vdisk file="{0}"' -f $resolvedPath) 'detach vdisk' ) if (-not $result.Success) { Stop-PSFFunction -String 'Dismount-Vhdx.Failed' -StringValues $resolvedPath, $result.ExitCode, ($result.Message -join "`n"), $result.Errors -EnableException $EnableException -Target $filePath -Cmdlet $PSCmdlet -Continue } } } } function Invoke-Diskpart { <# .SYNOPSIS Execute diskpart with the commands specified. .DESCRIPTION Execute diskpart with the commands specified. Commands are run sequentially, as if manually entered into the diskpart console. A final "exit" is implicitly ran and needs not be specified. .PARAMETER ArgumentList Commands to execute, in the order they should be executed. .EXAMPLE PS C:\> 'select vdisk file="C:\disks\w10.vhdx"', 'attach vdisk' | Invoke-Diskpart Mounts the C:\disks\w10.vhdx file #> [CmdletBinding()] param ( [Parameter(Mandatory = $true, ValueFromPipeline = $true)] [string[]] $ArgumentList ) begin { Assert-Elevation -Cmdlet $PSCmdlet $startInfo = [System.Diagnostics.ProcessStartInfo]::new() $startInfo.UseShellExecute = $false $startInfo.RedirectStandardError = $true $startInfo.RedirectStandardInput = $true $startInfo.RedirectStandardOutput = $true $startInfo.WindowStyle = 'hidden' $startInfo.FileName = 'diskpart.exe' $process = [System.Diagnostics.Process]::new() $process.StartInfo = $startInfo $null = $process.Start() } process { foreach ($line in $ArgumentList) { $process.StandardInput.WriteLine($line) } } end { $process.StandardInput.WriteLine('exit') while (-not $process.HasExited) { Start-Sleep -Milliseconds 100 } $messages = $process.StandardOutput.ReadToEnd() -split 'DISKPART>' | ForEach-Object Trim | Microsoft.PowerShell.Utility\Select-Object -Skip 1 foreach ($message in $messages) { Write-PSFMessage -String 'Invoke-Diskpart.Message' -StringValues $message } [PSCustomObject]@{ Success = $process.ExitCode -eq 0 Message = $messages Errors = $process.StandardError.ReadToEnd() ExitCode = $process.ExitCode } $process.Dispose() } } function Mount-Vhdx { <# .SYNOPSIS Mounts VHDX files as drives. .DESCRIPTION Mounts VHDX files as drives. Use Dismount-Vhdx to undo this once done with the disk. .PARAMETER Path Path to the file to mount .PARAMETER EnableException This parameters disables user-friendly warnings and enables the throwing of exceptions. This is less user friendly, but allows catching exceptions in calling scripts. .EXAMPLE PS C:\> Mount-Vhdx -Path 'c:\disks\profile.vhdx' Mounts the file 'c:\disks\profile.vhdx' #> [CmdletBinding()] param ( [Parameter(Mandatory = $true, ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true)] [PsfValidateScript('PSFramework.Validate.FSPath.File', ErrorString = 'PSFramework.Validate.FSPath.File')] [Alias('FullName')] [string[]] $Path, [switch] $EnableException ) begin { Assert-Elevation -Cmdlet $PSCmdlet } process { foreach ($filePath in $Path) { Write-PSFMessage -String 'Mount-Vhdx.Mounting' -StringValues $filePath $resolvedPath = Resolve-PSFPath -Path $filePath -Provider FileSystem -SingleItem $result = Invoke-Diskpart -ArgumentList @( ('select vdisk file="{0}"' -f $resolvedPath) 'attach vdisk' ) if (-not $result.Success) { Stop-PSFFunction -String 'Mount-Vhdx.Failed' -StringValues $resolvedPath, $result.ExitCode, ($result.Message -join "`n"), $result.Errors -EnableException $EnableException -Target $filePath -Cmdlet $PSCmdlet -Continue } } } } function New-Vhdx { <# .SYNOPSIS Creates a new vdhx file. .DESCRIPTION Creates a new vdhx file. It comes preconfigured with a single volume and can have files and folders pre-assigned to it. .PARAMETER Path Path to the VHDX file to create. Folder must exist, file should not. .PARAMETER Type How should the disk be provisioned. - Dynamic: File grows with its content (less consumption) - Fixed: File size equals size limit (slightly better performance) Defaults to: Dynamic .PARAMETER Size How large should the disk be? Defaults to 5GB Note: With "dynamic" disk type, the file backing it grows as its content is added, so this size limit need not be the actual storage consumed. .PARAMETER Label What label to add to the volume created in this disk. Defaults to: "Data" .PARAMETER Content Any files or folders to add to the disk. .EXAMPLE PS C:\> Get-ChildItem C:\install\sccm\ | New-Vhdx -Path 'C:\disks\sccm-content.vhdx' Creates a new vhdx file as 'C:\disks\sccm-content.vhdx', adding all files and folders from 'C:\install\sccm\' to it. #> [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSUseShouldProcessForStateChangingFunctions", "")] [CmdletBinding()] param ( [Parameter(Mandatory = $true)] [PsfValidateScript('PSFramework.Validate.FSPath.FileOrParent', ErrorString = 'PSFramework.Validate.FSPath.FileOrParent')] [string] $Path, [ValidateSet('Dynamic', 'Fixed')] [string] $Type = 'Dynamic', [PSFSize] $Size = 5GB, [string] $Label = 'Data', [Parameter(ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true)] [Alias('FullName')] [string[]] $Content ) begin { Assert-Elevation -Cmdlet $PSCmdlet $typeMapping = @{ Dynamic = 'expandable' Fixed = 'fixed' } $resolvedPath = Resolve-PSFPath -Path $Path -Provider FileSystem -SingleItem -NewChild # Normalize path to avoid legacy-shortening of folder names breaking later comparisons $parent = Split-Path -Path $resolvedPath $fileName = Split-Path -Path $resolvedPath -Leaf $resolvedPath = Join-Path -Path (Get-Item -Path $parent).FullName -ChildPath $fileName $diskPartCommand = 'create vdisk file="{0}" maximum={1} type={2}' -f $resolvedPath, $Size.Megabyte, $typeMapping[$Type] $result = Invoke-Diskpart -ArgumentList $diskPartCommand if (-not $result.Success) { Stop-PSFFunction -String 'New-Vhdx.CreateDisk.Failed' -StringValues $resolvedPath, $result.Errors -EnableException $true } $result = Invoke-Diskpart -ArgumentList @( ('select vdisk file="{0}"' -f $resolvedPath) 'attach vdisk' 'create partition primary' ('format fs=NTFS label="{0}" quick' -f $Label) 'assign' ) if (-not $result.Success) { Stop-PSFFunction -String 'New-Vhdx.PrepareDisk.Failed' -StringValues $resolvedPath, $result.Errors -EnableException $true } $start = Get-Date do { Start-Sleep -Milliseconds 200 $disk = Get-Disk | Where-Object Location -EQ $resolvedPath $volume = $disk | Get-Partition | Get-Volume if ($start.AddMinutes(1) -lt (Get-Date)) { Write-PSFMessage -Level Warning -String 'New-Vhdx.Volume.Timeout' break } $rootPath = '{0}:\' -f $volume.DriveLetter $null = Get-PSProvider | Write-Output if ($volume.DriveLetter -and -not (Test-Path -Path $rootPath)) { $null = New-PSDrive -Name $volume.DriveLetter -PSProvider FileSystem -Root $rootPath -ErrorAction Ignore } } until ($volume.DriveLetter -and (Test-Path -Path $rootPath)) } process { foreach ($inputItem in $Content) { Write-PSFMessage -String 'New-Vhdx.Copying' -StringValues $inputItem, $rootPath Invoke-PSFProtectedCommand -ActionString 'New-Vhdx.Copying' -ActionStringValues $inputItem, $rootPath -Target $volume.DriveLetter -ScriptBlock { Copy-Item -Path $inputItem -Destination $rootPath -Force -Recurse -ErrorAction Stop } -PSCmdlet $PSCmdlet -Continue } } end { Dismount-Vhdx -Path $resolvedPath -EnableException } } function Remove-VhdxContent { <# .SYNOPSIS Removes files or folders from the specified vhdx file. .DESCRIPTION Removes files or folders from the specified vhdx file. If the VHDX hasn't been mounted yet, it will be mounted before removing content and dismounted once done. Note: Only supports single-volume VHDX files. .PARAMETER Path Path to the VHDX file. .PARAMETER SubPath Relative path _within_ the volume of the VHDX file, where to remove the files & folders specified. Defaults to the volume root. .PARAMETER Content Relative path to files or folders to remove. .PARAMETER EnableException This parameters disables user-friendly warnings and enables the throwing of exceptions. This is less user friendly, but allows catching exceptions in calling scripts. .PARAMETER Confirm If this switch is enabled, you will be prompted for confirmation before executing any operations that change state. .PARAMETER WhatIf If this switch is enabled, no actions are performed but informational messages will be displayed that explain what would happen if the command were to run. .EXAMPLE PS C:\> Remove-VhdxContent -Path 'c:\disks\data.vhdx' -Content 'secret.txt' Removes the file "secret.txt" from the volume root path of the specified disk. .EXAMPLE PS C:\> Remove-VhdxContent -Path 'c:\disks\data.vhdx' -SubPath config\secrets -Content '*.txt' Removes all txt files from the subfolder config\secrets of the volume of the specified disk. Assuming that volume, once mounted, has the drive letter "T", every text file in "T:\config\secrets" would be deleted. #> [CmdletBinding(SupportsShouldProcess = $true)] param ( [Parameter(Mandatory = $true)] [PsfValidateScript('PSFramework.Validate.FSPath.File', ErrorString = 'PSFramework.Validate.FSPath.File')] [string] $Path, [string] $SubPath, [Parameter(Mandatory = $true, ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true)] [string[]] $Content, [switch] $EnableException ) begin { Assert-Elevation -Cmdlet $PSCmdlet $resolvedPath = Resolve-PSFPath -Path $Path -Provider FileSystem -SingleItem $wasMounted = $false $disk = Get-Disk | Where-Object Location -EQ $resolvedPath if (-not $disk) { Mount-Vhdx -Path $resolvedPath $disk = Get-Disk | Where-Object Location -EQ $resolvedPath if ($disk) { $wasMounted = $true } } if (-not $disk) { Stop-PSFFunction -String 'Remove-VhdxContent.Mount.Failed' -StringValues $resolvedPath -EnableException $EnableException -Cmdlet $PSCmdlet -Target $resolvedPath return } $volume = $disk | Get-Partition | Get-Volume if (@($volume).Count -gt 1) { Stop-PSFFunction -String 'Remove-VhdxContent.Volumes.Multiple.Error' -StringValues $resolvedPath -EnableException $EnableException -Cmdlet $PSCmdlet -Target $resolvedPath return } $rootPath = '{0}:\' -f $volume.DriveLetter if ($SubPath) { $rootPath = Join-Path -Path $rootPath -ChildPath $SubPath } } process { if (Test-PSFFunctionInterrupt) { return } foreach ($item in $Content) { $itemPath = Join-Path -Path $rootPath -ChildPath $item Invoke-PSFProtectedCommand -ActionString 'Remove-VhdxContent.Removing.Item' -ActionStringValues $itemPath -Target $resolvedPath -ScriptBlock { Remove-Item -Path $itemPath -Recurse -Force -Confirm:$false -ErrorAction Stop } -EnableException $EnableException -PSCmdlet $PSCmdlet -Continue } } end { if ($wasMounted) { Dismount-Vhdx -Path $resolvedPath } } } <# This is an example configuration file By default, it is enough to have a single one of them, however if you have enough configuration settings to justify having multiple copies of it, feel totally free to split them into multiple files. #> <# # Example Configuration Set-PSFConfig -Module 'VHDX' -Name 'Example.Setting' -Value 10 -Initialize -Validation 'integer' -Handler { } -Description "Example configuration setting. Your module can then use the setting using 'Get-PSFConfigValue'" #> Set-PSFConfig -Module 'VHDX' -Name 'Import.DoDotSource' -Value $false -Initialize -Validation 'bool' -Description "Whether the module files should be dotsourced on import. By default, the files of this module are read as string value and invoked, which is faster but worse on debugging." Set-PSFConfig -Module 'VHDX' -Name 'Import.IndividualFiles' -Value $false -Initialize -Validation 'bool' -Description "Whether the module files should be imported individually. During the module build, all module code is compiled into few files, which are imported instead by default. Loading the compiled versions is faster, using the individual files is easier for debugging and testing out adjustments." <# Stored scriptblocks are available in [PsfValidateScript()] attributes. This makes it easier to centrally provide the same scriptblock multiple times, without having to maintain it in separate locations. It also prevents lengthy validation scriptblocks from making your parameter block hard to read. Set-PSFScriptblock -Name 'VHDX.ScriptBlockName' -Scriptblock { } #> <# # Example: Register-PSFTeppScriptblock -Name "VHDX.alcohol" -ScriptBlock { 'Beer','Mead','Whiskey','Wine','Vodka','Rum (3y)', 'Rum (5y)', 'Rum (7y)' } #> <# # Example: Register-PSFTeppArgumentCompleter -Command Get-Alcohol -Parameter Type -Name VHDX.alcohol #> New-PSFLicense -Product 'VHDX' -Manufacturer 'Friedrich Weinmann' -ProductVersion $script:ModuleVersion -ProductType Module -Name MIT -Version "1.0.0.0" -Date (Get-Date "2021-05-21") -Text @" Copyright (c) 2021 Friedrich Weinmann Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. "@ #endregion Load compiled code |