Win10+ Setup Disk (Works with UEFI Secure Boot / BIOS / Install.wim over 4 GB)

Discussion in 'Scripting' started by freddie-o, Mar 21, 2019.

  1. #301 Deleted member 1385001, Oct 11, 2020
    Last edited by a moderator: Oct 12, 2020
    Why Pastebin Mark it as Potentially Offensive Content :
    a.png

    Edit Now Saying removed Content:
    b.png
     
  2. rpo

    rpo MDL Expert

    Jan 3, 2010
    1,447
    1,424
    60
    I reuploaded here : https://pastebin.com/q8uzgtmL
    A stupid filter considers the content as "Potentially offensive" and it is possible the paste to be redeleted.
    You can get the content at post #1.
     
  3. Just to help Dev about the link he posted on First post i told him so that users wont complain about that in future . Thanks a lot.
    Now it looks good as he uploaded the script to our forum so that theres no any possibility to be deleted.
    Thanks to Dev too for his concern.
     
  4. If you are a Noob then where am i ? ;)
     
  5. rpo

    rpo MDL Expert

    Jan 3, 2010
    1,447
    1,424
    60
    You'r too modest!!
     
  6. freddie-o

    freddie-o MDL Expert

    Jul 29, 2009
    1,375
    2,277
    60
    Seriously, I'm not. I can understand a little how code works. Usually I create scripts by trial and error -- it takes me hours sometimes. Most of the time I look online for solutions. There are a lot of samples & tutorials online. @rpo is the coder here. I just suggest ideas :oops: That's why I have a collection of sample scripts that I keep for referral
     
  7. freddie-o

    freddie-o MDL Expert

    Jul 29, 2009
    1,375
    2,277
    60
    #310 freddie-o, Oct 15, 2020
    Last edited: Oct 15, 2020
    (OP)
    Did some house cleaning and cosmetics

    Code:
    <# : standard way of doing hybrid batch + powershell scripts
    @title Win10 Setup Disk 2.2 @ forums.mydigitallife.net &color f0
    @set "__ARGS__=%*" &powershell -noprofile "$ScriptPath='%~f0';iex((Get-Content('%~f0') -Raw))" &exit/b
    #>
    #
    #   Website: https://forums.mydigitallife.net/threads/win10-setup-disk-for-uefi-or-bios-uefi-with-secure-boot-install-wim-over-4-gb.79268/
    #
    #   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"))
    {
        $uac_error="Elevating UAC for Administrator Privileges failed"
        #   The following test is to avoid infinite looping if elevating UAC for Administrator Privileges failed
        if ($env:__ARGS__ -eq $uac_error) {
        read-host "$uac_error`r`nRight click on the script and select ""Run as administrator""`r`nPress Enter to exit...";exit}
    #   Restart the script to get Administrator privileges and exit
                                                                                        
        Start-Process "$ScriptPath" $uac_error -Verb runAs; exit
    }
    $pswindow = $host.ui.rawui          # create a reference to the console’s UI.RawUI child object
    $pswindow.windowtitle = ([string]($pswindow.windowtitle -split "^.*  ")).trim() ; $ShortTitle=($pswindow.windowtitle -split " @ .*")[0]
    #
    Add-Type -AssemblyName System.Windows.Forms # Load the class System.Windows.Forms
    #
    # Filebrowser dialog object
    $FileBrowser = New-Object System.Windows.Forms.OpenFileDialog -Property @{
        Multiselect = $false # One file can be chosen
        Filter = 'ISO images (*.iso)|*.iso' # Select only iso files
    }
    #
    Function MsgBox {[System.Windows.Forms.MessageBox]::Show($Args[0],$ShortTitle,$Args[1],$Args[2])}
    #
    clear-host
    $USB=$Null
    $Form=New-Object System.Windows.Forms.Form # Create the screen form (window)
    $Form.TopMost = $True
    # Set the title and size of the window:
    $Form.Text=$ShortTitle
    $Form.Font='Consolas,10'
    $Form.Width=420 ; $Form.Height=265
    $Form.StartPosition = "CenterScreen"
    $Form.SizeGripStyle = "Hide"
    [System.Windows.Forms.Application]::EnableVisualStyles();
    
    # Create a drop-down list and fill it
    $USBDiskList=New-Object System.Windows.Forms.ComboBox
    $USBDiskList.DropDownStyle=[System.Windows.Forms.ComboBoxStyle]::DropDownList;
    $USBDiskList.Location=New-Object System.Drawing.Point(20,50)
    $USBDiskList.Size=New-Object System.Drawing.Size(363,22)
    
    $Form.Controls.Add($SelectUSBDiskList)
    $USBDisks=@() # array with USB disk number
    $Disks=Get-Disk | Where-Object {($_.BusType -eq "USB") -and ($_.OperationalStatus -eq "Online")}
    
    While (!$Disks) {
    if((MsgBox "Please plug in your USB disk first. `n`nClick OK to continue." "OKCancel" "Information") -eq "Cancel") {exit}
        $Disks=Get-Disk | Where-Object {($_.BusType -eq "USB") -and ($_.OperationalStatus -eq "Online")}
    }
    
    $USBDisk=New-Object System.Windows.Forms.Label # Put the USB Disk label on the form
    $USBDisk.Location=New-Object System.Drawing.Point(20,30)
    $USBDisk.Text="USB Disk"                 
    $USBDisk.Size=New-Object System.Drawing.Size(200,20)
    $Form.Controls.Add($USBDisk)
    
    $ISOImage=New-Object System.Windows.Forms.Label # Put the ISO Image label on the form
    $ISOImage.Location=New-Object System.Drawing.Point(20,95)               
    $ISOImage.Size=New-Object System.Drawing.Size(200,20)
    $ISOImage.text="ISO Image"
    $Form.Controls.Add($ISOImage)
    
    $ISOFile=New-Object System.Windows.Forms.Label # Put the ISO file name on the form
    $ISOFile.Location=New-Object System.Drawing.Point(20,115)
    $ISOFile.Text=" "
    $ISOFile.Size=New-Object System.Drawing.Size(364,24)
    $ISOFile.Backcolor = [System.Drawing.Color]::White
    $ISOFile.BorderStyle = [System.Windows.Forms.BorderStyle]::FixedSingle
    $Form.Controls.Add($ISOFile)
    
    $CancelButton=New-Object System.Windows.Forms.Button # Put the Cancel button on the form
    $CancelButton.Location=New-Object System.Drawing.Point(285,180)
    $CancelButton.Text="Cancel"                       
    $CancelButton.Size=New-Object System.Drawing.Size(100,26)
    $Form.Controls.Add($CancelButton)
    $CancelButton.DialogResult = [System.Windows.Forms.DialogResult]::Cancel
    
    $SelectISOButton=New-Object System.Windows.Forms.Button # Put the Select ISO button on the form
    $SelectISOButton.Location=New-Object System.Drawing.Point(175,180)
    $SelectISOButton.Text="Select ISO"                         
    $SelectISOButton.Size=New-Object System.Drawing.Size(100,26)
    $Form.Controls.Add($SelectISOButton)
    
    $CreateDiskButton=New-Object System.Windows.Forms.Button # Put the Create Disk button on the form
    $CreateDiskButton.Location=New-Object System.Drawing.Point(65,180)
    $CreateDiskButton.Text="Create Disk"                               
    $CreateDiskButton.Size=New-Object System.Drawing.Size(100,26)
    $Form.Controls.Add($CreateDiskButton)
    $CreateDiskButton.Enabled = $false
    $CreateDiskButton.DialogResult = [System.Windows.Forms.DialogResult]::OK
    
    $SelectISOButton.Add_Click({
        If ($FileBrowser.ShowDialog() -ne "Cancel"){ # if Cancel, just ignore
            $Global:ImagePath = $FileBrowser.filename    # return the file name
            $ISOFile.Text= Split-Path -Path $ImagePath -leaf # extract filename and extension (iso)
            if (($ISOFile.Text).length -gt 44) {$ISOFile.Text = $ImagePath.PadRight(100," ").substring(0,43)+"..."}
            $CreateDiskButton.Enabled = $true
            $CreateDiskButton.Focus()}})
    
    Foreach ($USBDisk in $Disks) {
        $FriendlyName=($USBDisk.FriendlyName).PadRight(40," ").substring(0,39)
        $USBDisks+=$USBDisk.DiskNumber
        $USBDiskList.Items.Add(("{0,-39}{1:n2} GB" -f $FriendlyName,($USBDisk.Size/1GB)))|out-null
        $Partitions = Get-Partition | Where-Object { $_.DiskNumber -eq $USBDisk.DiskNumber}
        If ($Partitions) {
            Foreach ($Partition in $Partitions) {
            If(!$Partition.DriveLetter){$AccessPath="  "} Else {$AccessPath=$Partition.DriveLetter+":"}   
            $Volumes=get-volume | Where-Object {$Partition.AccessPaths -contains  $_.path }
                Foreach ($Volume in $Volumes) {
                    $USBDisks+=$USBDisk.DiskNumber
                    $USBDiskList.Items.Add(("{0,0}({1,2}){2,-32}[{3:n2} GB]" -f " ", ($AccessPath), $Volume.FileSystemLabel.PadRight(25," ").substring(0,25), ($Partition.Size/1GB)))|out-null
                }
            }
        }
    }
    $form.Controls.Add($USBDiskList)
    $USBDiskList.SelectedIndex=0
    #
    $Groupbox=New-Object System.Windows.Forms.Groupbox # Add a group box on the form
    $Groupbox.Location=New-Object System.Drawing.Point(7,0)
    $Groupbox.Text=""
    $Groupbox.Size=New-Object System.Drawing.Size(390,220)
    $Form.Controls.Add($Groupbox)
    #
    if($form.ShowDialog() -eq "Cancel") {MsgBox "The script was cancelled." "OK" "Information"|out-Null;exit}
    #
    # At this point the mounted USB disk and the iso image file path are defined
    #
    $USB=$USBDisks[$USBDiskList.SelectedIndex]
    #
    If((MsgBox "WARNING! `n`nYour USB disk will be converted to MBR scheme, repartitioned and reformatted.`n`nAll partitions and data currently stored in the USB disk will be erased.`r`n`r`nAre you sure you want to continue?" "YESNO" "Warning") -eq "NO"){exit}
    # Mount the image file if not already mounted and get the drive letter
    #
    #  Check if iso already mounted
        $ISO=(Get-DiskImage -ImagePath $ImagePath | Get-Volume).DriveLetter  # get drive letter if ISO mounted
    #    Mount iso
        $Mounted=$True
        If (!$ISO) {$Mounted=$False;Mount-DiskImage -ImagePath $ImagePath -StorageType ISO |out-null
        $ISO = (Get-DiskImage -ImagePath $ImagePath | Get-Volume).DriveLetter}
        $ISO=$ISO+":"
    If ($ISO -eq ":") {exit}
    #
    # set bootmenupolicy Legacy
    Copy-Item $ISO"\boot\bcd" $env:temp\bcdmbr -Force
    & bcdedit /store ($env:temp + "\bcdmbr") /set '{default}' bootmenupolicy Legacy
    Set-ItemProperty -Path ($env:temp + "\bcdmbr") -Name IsReadOnly -Value $true
    Copy-Item $ISO"\EFI\Microsoft\boot\bcd" $env:temp\bcdefi -Force
    & bcdedit /store ($env:temp + "\bcdefi") /set '{default}' bootmenupolicy Legacy
    Set-ItemProperty -Path ($env:temp + "\bcdefi") -Name IsReadOnly -Value $true
    #
    Clear-Host
    #    Clear the USB stick
    Clear-Disk $usb -RemoveData -RemoveOEM -Confirm:$false
    set-disk $usb -partitionstyle mbr
    Stop-Service ShellHWDetection -erroraction silentlycontinue|out-null
    #   Create the fat32 boot partition
    $usbfat32=(New-Partition -DiskNumber $usb -Size  1GB -AssignDriveLetter | Format-Volume -FileSystem FAT32 -NewFileSystemLabel "BOOT").DriveLetter + ":"
    #    Copy needed files to the fat32 boot partition
    robocopy $iso"\" $usbfat32"\" bootmgr bootmgr.efi
    robocopy $iso"\boot" $usbfat32"\boot" /e /xf $iso\boot\bcd
    robocopy $iso"\efi" $usbfat32"\efi" /e /xf $iso\efi\microsoft\boot\bcd
    robocopy $iso"\sources" $usbfat32"\sources" boot.wim
    Copy-Item ($env:temp + "\bcdmbr") $usbfat32"\boot\bcd" -Force
    Copy-Item ($env:temp + "\bcdefi") $usbfat32"\EFI\Microsoft\boot\bcd" -Force
    #     Remove the drive letter to hide the device
    Get-Volume -DriveLetter $usbfat32.substring(0,$usbfat32.Length-1) | Get-Partition | Remove-PartitionAccessPath -accesspath $usbfat32
    #
    #    Create the NTFS intall partition
    $usbntfs=(New-Partition -DiskNumber $usb -UseMaximumSize -AssignDriveLetter -IsActive | Format-Volume -FileSystem NTFS -NewFileSystemLabel "SETUP").DriveLetter + ":"
    Start-Service ShellHWDetection -erroraction silentlycontinue|out-null
    #
    #    Copy needed files to the NTFS install partition
    robocopy $iso $usbntfs /e /xf $iso\boot\bcd $iso\efi\microsoft\boot\bcd
    Copy-Item ($env:temp + "\bcdmbr") $usbntfs"\boot\bcd" -Force
    Copy-Item ($env:temp + "\bcdefi") $usbntfs"\EFI\Microsoft\boot\bcd" -Force
    #
    #    House keeping
    remove-item ($env:temp + "\bcdmbr") -force
    remove-item ($env:temp + "\bcdmbr.*") -force
    remove-item ($env:temp + "\bcdefi") -force
    remove-item ($env:temp + "\bcdefi.*") -force
    #
    # Eject the mounted iso image if it was loaded by the script
    If(!$Mounted){DisMount-DiskImage -ImagePath $ImagePath |out-null}
    MsgBox (($ShortTitle -split " @.*")[0]+" completed successfully.") "OK" "Information" |Out-Null;exit
    
    
     
  8. rpo

    rpo MDL Expert

    Jan 3, 2010
    1,447
    1,424
    60
    Just trying to have a more "elegant" code :

    Replace lines 54-59 by :
    Code:
    #
    $Disks=$Null;While (!$Disks){
        If(!($Disks=Get-Disk | Where-Object {($_.BusType -eq "USB") -and ($_.OperationalStatus -eq "Online")})){
            if((MsgBox "Please plug in your USB disk first. `n`nClick OK to continue." "OKCancel" "Information") -eq "Cancel") {exit}}}
    and lines 142-151 by :
    Code:
    #   Check if iso already mounted by getting driveletter
    If($ISO=(Get-DiskImage -ImagePath $ImagePath | Get-Volume).DriveLetter){$Mounted=$True}    Else
    #    Mount iso and get drive letter
        {$Mounted=$False; Mount-DiskImage -ImagePath $ImagePath -StorageType ISO |out-null
         If(!($ISO=(Get-DiskImage -ImagePath $ImagePath | Get-Volume).DriveLetter)){Exit}}
    $ISO=$ISO+":"    
     
  9. tigercheng

    tigercheng MDL Member

    May 4, 2015
    145
    184
    10
    freddie-o, if my Windows 10 ISO has install.esd instead of install.wim (i.e. less than 4GB), your script as per above(for install.wim under 4 GB) still applicable or not if I want to create a bootable USB disk?

    or

    I just need to format my USB disk to FAT32 and copy the contents of my Windows ISO to the disk and make sure that
    Which method of creating bootable USB drive is more time saving and practical?
     
    Stop hovering to collapse... Click to collapse... Hover to expand... Click to expand...
  10. freddie-o

    freddie-o MDL Expert

    Jul 29, 2009
    1,375
    2,277
    60
    The script just automates formatting your USB disk to FAT32 and copying the contents of your ISO to the disk.
    So either or will produce the same results.
    Personally I prefer using a script. But that's just me.
     
  11. tigercheng

    tigercheng MDL Member

    May 4, 2015
    145
    184
    10
    Understood. Thanks for the advice :)
     
    Stop hovering to collapse... Click to collapse... Hover to expand... Click to expand...
  12. spanishfly

    spanishfly MDL Senior Member

    Dec 5, 2018
    352
    527
    10
    I have a special request. Is it possible to add an option or make a separate version of this script that instead of mounting (expanding) an ISO just uses the contents of already expanded Windows ISO folder? I'm a noob coder with what I though were enough skills to decipher how to do this on my own by studying your code, but, man, the code you guys wrote is pretty tight!
    I'm hoping that for whoever helped or primarily coded this project, my request is trivial. If it's not trivial, than just let me know and I'll thank you for at least considering my request!
    Suggested feature list as per my request.
    1. Converts your USB disk to MBR scheme.
    2. Creates 2 partitions on your USB disk -- a FAT32 and an NTFS partition.
    3. Accepts as source either: a Windows ISO or the folder contents of an pre-extracted (expanded) Windows ISO
    4. Mounts your Windows ISO or gathers the folder contents of the pre-extracted Windows ISO
    5. Copies the entire contents of the Windows ISO to the NTFS partition of the USB disk.
    6. Copies all the boot files (“boot” folder, “efi” folder, “bootmgr”, “bootmgr.efi” and “boot.wim”) from the Windows ISO to the FAT32 partition of the USB disk.
    7. Adds Legacy BootMenuPolicy to the BCD store to show a progress bar while booting on Legacy BIOS systems.
     
    Stop hovering to collapse... Click to collapse... Hover to expand... Click to expand...
  13. freddie-o

    freddie-o MDL Expert

    Jul 29, 2009
    1,375
    2,277
    60
  14. sebus

    sebus MDL Guru

    Jul 23, 2008
    6,356
    2,026
    210
    Do you really need script to do it for you?

    It takes a moment to do it "by hand" in worse case (surely you do not create it daily?)

    Anyway, the "script" is missing from this thread all together!