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

Discussion in 'MDL Projects and Applications' started by rpo, Mar 18, 2019.

  1. rpo

    rpo MDL Expert

    Jan 3, 2010
    1,505
    1,514
    60
    @BAU
    Your original (modified) coding to get admin privilege :
    Code:
    <# : standard way of doing hybrid batch + powershell scripts
    @echo off
    ::AveYo: self-elevate passing args and preventing loop
    set "args="%~f0" %*" & call set "args=%%args:"=\"%%"
    fsutil dirty query %systemdrive%>nul||(if "%?%" neq "y" powershell -c "start cmd -ArgumentList '/c set ?=y&call %args%' -verb runas" &exit)
    powershell -NoLogo -NoProfile -WindowStyle Normal -ExecutionPolicy Bypass -c "iex([io.file]::ReadAllText(\"%~f0\"))" &exit/b
    #>
    has the advantage to prevent loop, but this is not the case with :
    Code:
    <# : standard way of doing hybrid batch + powershell scripts
    @set "__CMD__=%~f0" &set "__ARGS__=%*" &powershell -noprofile -c "iex([io.file]::ReadAllText(\"%~f0\"))" &exit/b
    #>
    #
    #    This script must be executed with admin privilege
    #
    #    Test Administrator privileges
    If (-NOT ([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole(544))
    {
    #    Restart the script to get Administrator privileges and exit
         Start-Process cmd -ArgumentList ("/c call `"$Env:__CMD__`" $Env:__ARGS__") -Verb runAs
         exit
    }
    How is this to be modified to prevent loop? I suppose we have to deal with argument passing...
     
  2. AveYo

    AveYo MDL Expert

    Feb 10, 2009
    1,836
    5,737
    60
    there should be no loop since the check is in powershell - IsInRole(544) takes care of that ( if not admin - restart as admin, if already admin, do nothing )
     
    Stop hovering to collapse... Click to collapse... Hover to expand... Click to expand...
  3. rpo

    rpo MDL Expert

    Jan 3, 2010
    1,505
    1,514
    60
    Thanks. Efficient, as usual.
     
  4. freddie-o

    freddie-o MDL Expert

    Jul 29, 2009
    1,606
    2,676
    60
    Can "System.Windows.Forms.ComboBox" automatically detect when a USB is plugged or unplugged?
     
    Stop hovering to collapse... Click to collapse... Hover to expand... Click to expand...
  5. rpo

    rpo MDL Expert

    Jan 3, 2010
    1,505
    1,514
    60
    Here is one of my "old" scripts (just deleted the echo statements and changed some variable names) :
    Code:
    <# : standard way of doing hybrid batch + powershell scripts
    @set "__CMD__=%~f0" &set "__ARGS__=%*" &powershell -noprofile -c "iex([io.file]::ReadAllText(\"%~f0\"))" &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 'powershell.exe' -Verb runAs -ArgumentList ("-NoLogo -WindowStyle Normal -noprofile -file " + """" + $PSCommandPath + """")
        exit
    }
    #    We have Administrator privileges
    #
    $pswindow = $host.ui.rawui          # create a reference to the console’s UI.RawUI child object
    $newsize = $pswindow.buffersize    # set the buffer size
    $newsize.height = 3000                # 3000 lines
    $newsize.width = 150                # 150 characters
    $pswindow.buffersize = $newsize    # set the BufferSize properties
    $newsize = $pswindow.buffersize    # assign the BufferSize properties to a variable named $newsize
    $pswindow.buffersize = $newsize    # assign the values to the actual console window
    $newsize = $pswindow.windowsize    # set the window size
    $newsize.height = [Math]::Min(50, $host.ui.rawui.MaxWindowSize.height)
    $newsize.width = [Math]::Min(150, $host.ui.rawui.MaxWindowSize.Width)
    $pswindow.windowsize = $newsize
    $pswindow.windowtitle = "Create USB boot disk"
    $pswindow.foregroundcolor = "Yellow";$pswindow.backgroundcolor = "Blue"
    #
    Add-Type -AssemblyName System.Windows.Forms # Load the class System.Windows.Forms
    # Filebrowser dialog
    $FileBrowser = New-Object System.Windows.Forms.OpenFileDialog -Property @{
       Multiselect = $false # One file can be chosen
        Filter = 'ISO images (*.iso)|*.iso' # Select iso files
    title="Select the .iso image"
    }
    #
    Function ErrorMessage
    {
    Param([string]$msg)
    Write-Host -NoNewline $msg  -ForegroundColor Red -backgroundColor White
    $HOST.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown") | out-null
    $HOST.UI.RawUI.Flushinputbuffer()
    }
    clear-host
    $wshell=New-Object -ComObject Wscript.Shell
    #    Select the USB stick
    $form=New-Object System.Windows.Forms.Form # Create the screen form (window)
    # $Form.ControlBox = $false
    $Form.FormBorderStyle = "none"
    $form.Text="Available USB disk(s)"
    $Form.Width=640 ; $Form.Height=300
    $Form.backColor="LightYellow"
    $Form.AutoSize=$false
    $Form.startposition = "Manual"
    $form.Location=New-Object System.Drawing.Point(10,10)
    $USBDiskList=New-Object System.Windows.Forms.ComboBox
    $USBDiskList.DropDownStyle=[System.Windows.Forms.ComboBoxStyle]::DropDownList;
    $USBDiskList.Location=New-Object System.Drawing.Point(5,20)
    $USBDiskList.Width=630;$USBDiskList.height=20 
    # $USBDiskList.backColor="blue" ; $USBDiskList.ForeColor="White"
    $USBDiskList.Font='Courier New,10'
    $Form.KeyPreview = $True
    $Form.Add_KeyDown({if ($_.KeyCode -eq "Enter"){$OKButton.PerformClick()}})
    $Form.Add_KeyDown({if ($_.KeyCode -eq "Escape"){$CancelButton.PerformClick()}})
    $OKButton=New-Object System.Windows.Forms.Button # Put the OK button on the form
    $OKButton.Location=New-Object System.Drawing.Size(560,200)
    $OKButton.Text="OK";$OKButton.Font='Microsoft Sans Serif,10'
    $OKButton.width=60;$OKButton.height=30;
    $OKButton.Add_MouseHover({$OKButton.backcolor = [System.Drawing.Color]::CornflowerBlue})
    $OKButton.Add_MouseLeave({$OKButton.backcolor = [System.Drawing.Color]::LightYellow})
    $form.Controls.Add($OKButton)
    $OKButton.DialogResult = [System.Windows.Forms.DialogResult]::OK
    $CancelButton=New-Object System.Windows.Forms.Button # Put the Cancel button on the form
    $CancelButton.Location=New-Object System.Drawing.Size(460,200)
    $CancelButton.Text="Cancel";$CancelButton.Font='Microsoft Sans Serif,10'
    $CancelButton.width=60;$CancelButton.height=30;
    $CancelButton.Add_MouseHover({$CancelButton.backcolor = [System.Drawing.Color]::CornflowerBlue})
    $CancelButton.Add_MouseLeave({$CancelButton.backcolor = [System.Drawing.Color]::LightYellow})
    $form.Controls.Add($CancelButton)
    $CancelButton.DialogResult = [System.Windows.Forms.DialogResult]::Cancel
    $Label = New-Object System.Windows.Forms.label
    $Label.AutoSize = $True
    $Label.Location = new-object System.Drawing.Size(20,60)
    $Label.Size = New-Object System.Drawing.Size(150,20)
    $Label.BorderStyle = "None"
    $Label.Font = "Arial,10"
    # $Label.backColor="blue" ; $Label.ForeColor="White"
    $form.Controls.Add($Label)
    $USB=$Null
    $USBDisks=@() # array whith USB disk number
    $Disks=Get-Disk | Where-Object {($_.BusType -eq "USB") -and ($_.OperationalStatus -eq "Online")}
    While (!$Disks) {
        $Label.BorderStyle = "Fixed3D"
        $Label.Text="Please mount USB stick. Click ""OK"" when ready`r`nor ""Cancel"" to exit."   
        $result = $form.ShowDialog()
        if ($result -eq "Cancel"){exit}
        $Disks=Get-Disk | Where-Object {($_.BusType -eq "USB") -and ($_.OperationalStatus -eq "Online")}
    }
    Foreach ($USBDisk in $Disks) {
        $FriendlyName=($USBDisk.FriendlyName).PadRight(30," ").substring(0,30)   
        $Partitions = Get-Partition | Where-Object { $_.DiskNumber -eq $USBDisk.DiskNumber}
        If ($Partitions) {
            Foreach ($Partition in $Partitions) {
            $Volumes=get-volume | Where-Object {$Partition.AccessPaths -contains  $_.path }
            Foreach ($Volume in $Volumes) {
                $USBDisks+=$USBDisk.DiskNumber
                $USBDiskList.Items.Add((" {0,-30}|{1,1}:| {2,-30}| {3:n2} GB" -f $FriendlyName, ($Partition.DriveLetter), $Volume.FileSystemLabel.PadRight(30," ").substring(0,30), ($Partition.Size/1GB)))|out-null
                }       
            }   
        } Else {
            $USBDisks+=$USBDisk.DiskNumber
            $USBDiskList.Items.Add((" {0,-30}| {1,1}| {2,-30}| {3:n2} GB" -f $FriendlyName, " ", " ",($USBDisk.Size/1GB)))|out-null       
        }
    }
    $form.Controls.Add($USBDiskList)
    $USBDiskList.SelectedIndex=0
    $Label.BorderStyle = "Fixed3D"
    $Label.Text="Select your device and click ""OK""`r`nor ""Cancel"" to exit."
    $result = $form.ShowDialog()
    if ($result -eq "Cancel"){exit}
    $USB=$USBDisks[$USBDiskList.SelectedIndex]
    #    Clear the USB stick
    Clear-Disk $usb -RemoveData -RemoveOEM -Confirm:$false
    Stop-Service ShellHWDetection
    #    Create the fat32 boot partition
    $usbfat32=(New-Partition -DiskNumber $usb -Size 1GB -AssignDriveLetter -IsActive | Format-Volume -FileSystem FAT32 -NewFileSystemLabel "BOOTFAT").DriveLetter + ":"
    #    Create the ntfs intall partition
    $usbntfs=(New-Partition -DiskNumber $usb -UseMaximumSize -AssignDriveLetter | Format-Volume -FileSystem NTFS -NewFileSystemLabel "INSTALL").DriveLetter + ":"
    Start-Service ShellHWDetection
    # Read-Host "Eject the iso if it is mounted. When ready press Enter"
    # $Volumes = (Get-Volume).Where({$_.DriveLetter}).DriveLetter
    # Read-Host "Mount the iso. When ready press Enter"
    # $ISO = (Compare-Object -ReferenceObject $Volumes -DifferenceObject (Get-Volume).Where({$_.DriveLetter}).DriveLetter).InputObject
    # $ISO = (get-volume| Where-Object {($_.DriveType -eq "CD-ROM") -and ($_.filesystemlabel -ne "") -and ($_.OperationalStatus -eq "OK")} |Out-GridView -Title 'Select Cd-Rom image' -OutputMode Single).DriveLetter + ":"
    # $wshell.Popup("Select the iso.",0,"ISO image") | Out-Null
    #
    [void]$FileBrowser.ShowDialog()
    #
    $ImagePath = $FileBrowser.FileName;
    $ISO=":"
    If($FileBrowser.FileNames -like "*\*") {
    #  Check if iso already mounted
        $ISO = (Get-DiskImage -ImagePath $ImagePath | Get-Volume).DriveLetter
    #    Mount iso
        IF (!$ISO) {Mount-DiskImage -ImagePath $ImagePath -StorageType ISO |out-null
        $ISO = (Get-DiskImage -ImagePath $ImagePath | Get-Volume).DriveLetter}
        $ISO=$ISO+":"
    }
    if ($ISO -eq ":") {
    # $wshell.Popup("No ISO image mounted or operation cancelled",0,"Error") | Out-Null;exit}
    ErrorMessage  "No ISO image mounted or operation cancelled. Press any key to exit.";exit}
    # Copy-Item -Path $ISO\* -Destination "$($usbntfs)" -Recurse -Verbose
    # Copy-Item -Path $ISO"\bootmgr" -Destination $usbfat32"\" -Verbose
    # Copy-Item -Path $ISO"\bootmgr.efi" -Destination $usbfat32"\" -Verbose
    # Copy-Item -Path $ISO"\boot" -Destination $usbfat32"\boot" -Recurse  -Verbose
    # Copy-Item -Path $ISO"\efi" -Destination $usbfat32"\efi" -Recurse  -Verbose
    # new-item $usbfat32"\sources" -itemType Directory
    # Copy-Item -Path $ISO"\sources\boot.wim" -Destination $usbfat32"\sources\boot.wim"  -Verbose
    robocopy $iso $usbntfs /e
    robocopy $iso"\" $usbfat32"\" bootmgr bootmgr.efi
    robocopy $iso"\boot" $usbfat32"\boot" /e
    robocopy $iso"\efi" $usbfat32"\efi" /e
    robocopy $iso"\sources" $usbfat32"\sources" boot.wim
    # Eject the mounted iso image
    # (New-Object -ComObject Shell.Application).Namespace(17).ParseName($ISO).InvokeVerb("Eject")
    DisMount-DiskImage -ImagePath $ImagePath |out-null
    Remove-item ($env:TEMP + "\script.ps1")     
    
     
  6. vigipirate

    vigipirate MDL Senior Member

    Feb 24, 2011
    402
    100
    10
    #126 vigipirate, Aug 12, 2019
    Last edited: Aug 12, 2019
    hello v 1.3 not create boot fat 32 one partition ntfs ?
    sory no bug resolve problem
    usb in gpt and rufus ?
     
  7. freddie-o

    freddie-o MDL Expert

    Jul 29, 2009
    1,606
    2,676
    60
    Did you download the latest script in the OP? No problem with me.
     
    Stop hovering to collapse... Click to collapse... Hover to expand... Click to expand...
  8. vigipirate

    vigipirate MDL Senior Member

    Feb 24, 2011
    402
    100
    10
    New-Partition : A parameter is not valid for this type of partition.

    Extended information: The parameters MbrType and IsActive cannot be used on a GPT disk. Activity ID: {d17b7f55-1468-47af-b5d0-43b329772c32} Au caractère Ligne:132 : 12 + $usbfat32=(New-Partition -DiskNumber $usb -Size 700MB -AssignDriveLet ... + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : InvalidArgument : (StorageWMI:ROOT/Microsoft/Windows/Storage/MSFT_Disk) [New-Partition], CimException
    + FullyQualifiedErrorId : StorageWMI 41006,New-Partition
    New-Partition : A parameter is not valid for this type of partition.

    Extended information: The parameters MbrType and IsActive cannot be used on a GPT disk. Activity ID: {d17b7f55-1468-47af-b5d0-43b329772c32} Au caractère Ligne:132 : 12 + $usbfat32=(New-Partition -DiskNumber $usb -Size 700MB -AssignDriveLet ... + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : InvalidArgument : (StorageWMI:ROOT/Microsoft/Windows/Storage/MSFT_Disk) [New-Partition], CimException
    + FullyQualifiedErrorId : StorageWMI 41006,New-Partition
     
  9. rpo

    rpo MDL Expert

    Jan 3, 2010
    1,505
    1,514
    60
    The error message is self-explicative : MbrType and IsActive cannot be used on a GPT disk.
     
  10. freddie-o

    freddie-o MDL Expert

    Jul 29, 2009
    1,606
    2,676
    60

    Your USB disk is GPT. Convert it to MBR.
     
    Stop hovering to collapse... Click to collapse... Hover to expand... Click to expand...
  11. freddie-o

    freddie-o MDL Expert

    Jul 29, 2009
    1,606
    2,676
    60
    #132 freddie-o, Aug 13, 2019
    Last edited: Aug 13, 2019
    @rpo you think we should add "convert mbr" to the script?

    Edit:

    Also in the "ComboBox DropDownList" is it possible to show the USB disk/s instead of partitons?
    Or the disk/s (with) their partitions?
    so there's just 1 entry on the list.
     
    Stop hovering to collapse... Click to collapse... Hover to expand... Click to expand...
  12. rpo

    rpo MDL Expert

    Jan 3, 2010
    1,505
    1,514
    60
    @freddie-o
    "you think we should add "convert mbr" to the script?" : the main purpose of this script is to create a usb stick, so for me short answer : no. But you are free to add the convert.
    "in the "ComboBox DropDownList" is it possible to show the USB disk/s instead of partitons?" : this makes sense. Just comment or suppress the instructions dealing with partitions .
    Code:
    Foreach ($USBDisk in $Disks) {
        $FriendlyName=($USBDisk.FriendlyName).PadRight(30," ").substring(0,30)
    #    $Partitions = Get-Partition | Where-Object { $_.DiskNumber -eq $USBDisk.DiskNumber}
    #    If ($Partitions) {
    #        Foreach ($Partition in $Partitions) {
    #        $Volumes=get-volume | Where-Object {$Partition.AccessPaths -contains  $_.path }
    #        Foreach ($Volume in $Volumes) {
    #            $USBDisks+=$USBDisk.DiskNumber
    #            $USBDiskList.Items.Add((" {0,-30}|{1,1}:| {2,-30}| {3:n2} GB" -f $FriendlyName, ($Partition.DriveLetter), $Volume.FileSystemLabel.PadRight(30," ").substring(0,30), ($Partition.Size/1GB)))|out-null
    #            }     
    #        }
    #    } Else {
            $USBDisks+=$USBDisk.DiskNumber
            $USBDiskList.Items.Add((" {0,-30}| {1,1}| {2,-30}| {3:n2} GB" -f $FriendlyName, " ", " ",($USBDisk.Size/1GB)))|out-null
    #    }
    }
     
  13. freddie-o

    freddie-o MDL Expert

    Jul 29, 2009
    1,606
    2,676
    60
    But if you cannot create a Windows installation disk using a GPT disk, wouldn't "convert mbr" solve the problem?

    Edit:

    They would then have to do it manually or use a 3rd party tool.
     
    Stop hovering to collapse... Click to collapse... Hover to expand... Click to expand...
  14. vigipirate

    vigipirate MDL Senior Member

    Feb 24, 2011
    402
    100
    10
    Hello
    it is rufus who put me the key usb gpt not mbr his for that I had this error sy it was written in the optional script why not again thank you for your work my problem is solved with a third party tool aomei partition
     
  15. rpo

    rpo MDL Expert

    Jan 3, 2010
    1,505
    1,514
    60
    It seems the solution is easy :
    ...
    Clear-Disk $usb -RemoveData -RemoveOEM -Confirm:$false
    set-disk $usb -partitionstyle mbr
    Stop-Service ShellHWDetection |out-null
    ...
     
  16. freddie-o

    freddie-o MDL Expert

    Jul 29, 2009
    1,606
    2,676
    60

    drive letter/s?
     
    Stop hovering to collapse... Click to collapse... Hover to expand... Click to expand...
  17. rpo

    rpo MDL Expert

    Jan 3, 2010
    1,505
    1,514
    60
    Only partitions have drive letters. For disks, you have a disk number.
     
  18. freddie-o

    freddie-o MDL Expert

    Jul 29, 2009
    1,606
    2,676
    60
    how to add disk number?
     
    Stop hovering to collapse... Click to collapse... Hover to expand... Click to expand...
  19. rpo

    rpo MDL Expert

    Jan 3, 2010
    1,505
    1,514
    60
    The disknumber is $USBDisk.DiskNumber... But this number is not user friendly.