Automatically mount VHD/VHDX at startup

Discussion in 'Scripting' started by rpo, Mar 21, 2024.

  1. rpo

    rpo MDL Expert

    Jan 3, 2010
    1,484
    1,486
    60
    The problem with VHD/VHDX files is that mounting is lost after a (re)boot. This can be solved by a scheduled task started at system startup.
    The proposed script asks the user to enter the task name and select the desired file.
    Remak : I don't know if this works with bitlocker encrypted files.
    Code:
    <# :
    @color 3E&powershell -noprofile -exec bypass "$ScriptPath='%~f0';iex((GC('%~f0') -Raw))"&pause&exit/b
    #>
    #
    #   This script must be executed with admin privilege
    #
    #   Test Administrator privileges
    If (-NOT ([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator"))
    { 
    #   Restart the script to get Administrator privileges and exit
        Start-Process "$ScriptPath" -Verb runAs; exit
    }
    # Unregister the task if present
    $taskname=""
    While(!$taskname){$taskname=Read-Host "Enter the name of the task to be created "}
    Unregister-ScheduledTask -TaskName $taskname -Confirm:$false -ErrorAction SilentlyContinue
    [void](Add-Type -AssemblyName System.Windows.Forms)
    # Filebrowser dialog object
    $FileBrowser = New-Object System.Windows.Forms.OpenFileDialog -Property @{
        Title="Select VHD/VHDX file"   
        InitialDirectory = "MyComputer"     
        Filter = 'VHD\VHDX Files (*.vhd;s*.vhdx)|*.vhd;*.vhdx'     
        Multiselect = $False                         #
    }
    #
    # Create and register the task
    If ($FileBrowser.ShowDialog() -eq "Cancel"){exit}
    $vhdfile="'$($FileBrowser.filename)'"
    $actions = New-ScheduledTaskAction  `
     -Id "Auto-Mount a VHD or VHDX file at system startup" `
     -Execute "powershell.exe" `
     -Argument "-ExecutionPolicy ByPass -NoProfile ""Mount-DiskImage $vhdfile"""
    $trigger = New-ScheduledTaskTrigger -AtStartup
    $principal = New-ScheduledTaskPrincipal -UserID "NT AUTHORITY\SYSTEM" `
        -LogonType ServiceAccount -RunLevel Highest
    $settings = New-ScheduledTaskSettingsSet -AllowStartIfOnBatteries -Compatibility WIN8
    $task = New-ScheduledTask -Action $actions `
        -Principal $Principal -Trigger $trigger -Settings $settings
    Register-ScheduledTask $taskname -InputObject $task
    
     
  2. Dark Dinosaur

    Dark Dinosaur X Æ A-12

    Feb 2, 2011
    4,189
    6,018
    150
    i don't see point for doing this
    but nice idea
     
    Stop hovering to collapse... Click to collapse... Hover to expand... Click to expand...
  3. rpo

    rpo MDL Expert

    Jan 3, 2010
    1,484
    1,486
    60
    If you don't do this, you have to invoke disk manager or diskpart (or call a script) to make the virtual disk available. That's all.
     
  4. stayboogy

    stayboogy MDL Addicted

    May 1, 2011
    855
    228
    30
    this is actually pretty cool, but couldn't you just create a powershell script with the commands and place a shortcut in the startup folder, or just add the .ps file to registry startup path? better than a scheduled task if you ask me since it never goes through the scheduled task manager of the mmc.

    just a thought.

    cool nonetheless.

    I used to use multiple .vhd files for data storage for faster portability of all my files when moving/changing/updating/reinstalling multiboot OS configurations on my work machines, and hated having to double click the shortcut to mount them at boot. I think I finally made a .vbs script to do this same thing. I will have to look for it in my archives.
     
  5. rpo

    rpo MDL Expert

    Jan 3, 2010
    1,484
    1,486
    60
    I tryed to place a shortcut in the startup folder ("C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Startup") and also add the .ps file to registry startup path ("HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Run"), but no success (I avoid using scheduled tasks).
    Two additional remarks :
    - The PS script can to modifyied to perform multiple actions in the same task.
    - I used Mount-DiskImage instead of Mount-VHD if Hyper V is not active.
     
  6. stayboogy

    stayboogy MDL Addicted

    May 1, 2011
    855
    228
    30
    which windows version are you on?

    startup folder and key was borked in several builds before 21h2 on Windows 10. No rhyme or reason, just not working. I never could figure it out. but I can confirm it should be working just fine 21h2 forward.

    I will try it at some point and see if works for me as a startup.

    also, I think you have to use a .vbs/.cmd to start the .ps if you use the Run registry key. i had to use .vbs to get that key to work for when I used a .ps to do my PostSetup Tasks similar to an AutoUnattend

    see here: https://codeberg.org/stayboogy/stay.../Unattended/%SystemDrive%/Install/install.vbs
     
  7. rpo

    rpo MDL Expert

    Jan 3, 2010
    1,484
    1,486
    60
    #7 rpo, Mar 23, 2024
    Last edited: Mar 23, 2024
    (OP)
    I run 23H2 22631.3296
    I suppose that the problem is related to autorization : mounting a vhdx file requires administrator privileges.