#######################################################################
# Copyright (c) 2016, Dell Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without modification,
# are permitted provided that the following conditions are met:
#	 * Redistributions of source code must retain the above copyright
#	   notice, this list of conditions, and the following disclaimer.
#	 * Redistributions in binary form must reproduce the above copyright
#	   notice, this list of conditions and the following disclaimer in the
#	   documentation and/or other materials provided with the distribution:
#	 * Neither the name of the Dell Inc. nor the names of its contributors
#	   may be used to endorse or promote products derived from this
#	   software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
# IN NO EVENT SHALL Dell Inc. BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
# BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
# IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
# OF SUCH DAMAGE.
#######################################################################


[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Drawing") 
[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms")  

function
Write-W2VInfo
{
# Function to make the Write-Host output a bit prettier.
       [CmdletBinding()]
       param(
           [Parameter(Mandatory = $true, ValueFromPipeline = $true)]
           [string]
           [ValidateNotNullOrEmpty()]
           $text
       )
       Write-Host "INFO   : $($text)"
}

Write-W2VInfo "Launching UI..."

[System.Reflection.Assembly]::LoadWithPartialName("System.windows.forms") | Out-Null
$Form = New-Object System.Windows.Forms.Form
$Form.Text = "Dell Driver Update Utility"
$Form.StartPosition = 1
$Form.Size = New-Object System.Drawing.Size(1130, 520)
$Form.BackColor = "LightGray"
$Form.FormBorderStyle = 1
$Form.MaximizeBox          = $False
$Form.MinimizeBox          = $False


$font = New-Object System.Drawing.Font("Segoe UI",10,0,3,1,[System.Drawing.FontStyle]::Regular)

$Label = New-Object System.Windows.Forms.Label
$Label.Location = New-Object System.Drawing.Size(10,10) 
$Label.Size = New-Object System.Drawing.Size(490,80)
$Label.Text = "You can use this utility to inject USB 3.0 drivers into the Windows Server 2008 R2 Operating system
NOTE: Make sure that the drive has enough space (atleast 10GB) to create the image"
$Label.AutoSize = $false
$Label.Font = $font
 
$button1 = New-Object System.Windows.Forms.Button

### Create Directories ###

$path = [System.IO.Path]::GetDirectoryName($myInvocation.MyCommand.Definition)

$destDir = "$path\temp"
$extractedDisk = "$path\temp\WindowsISO"
$wimPath = "$path\temp\wim"
$installWimPath = "$path\temp\installWim"
$PathToOscdimg = "$path\tools\oscdimg"
$driverPath = "$path\drivers"
$global:ISOFile=''
$global:Cust_folder = ''



if (!((Test-Path $destDir) -and (Test-Path $extractedDisk) -and (Test-Path $wimPath) -and (Test-Path $installWimPath)))
{
    New-Item -ItemType Directory -Path $destDir, $extractedDisk, $wimPath, $installWimPath -Force
}
else
{
    write-host "Directory already exists"
}


### Create Groupbox ###
#region textBox1

$textBox1                     = New-Object System.Windows.Forms.TextBox
$System_Drawing_Point         = New-Object System.Drawing.Point
$System_Drawing_Point.X       = 550
$System_Drawing_Point.Y       = 10
$textBox1.Location            = $System_Drawing_Point
$textBox1.Name                = "textBox1"
$System_Drawing_Size          = New-Object System.Drawing.Size
$System_Drawing_Size.Height   = 480
$System_Drawing_Size.Width    = 570
$textBox1.Size                = $System_Drawing_Size
$textBox1.MultiLine           = $true
$textBox1.ScrollBars          = [System.Windows.Forms.ScrollBars]::both


$Form.Controls.Add($textBox1)
#endregion textBox1

#region groupBox1

$groupBox1                    = New-Object System.Windows.Forms.GroupBox
$System_Drawing_Point         = New-Object System.Drawing.Point
$System_Drawing_Point.X       = 5
$System_Drawing_Point.Y       = 100
$groupBox1.Location           = $System_Drawing_Point
$groupBox1.Name               = "groupBox1"
$System_Drawing_Size          = New-Object System.Drawing.Size
$System_Drawing_Size.Height   = 100
$System_Drawing_Size.Width    = 450
$groupBox1.Size               = $System_Drawing_Size
$groupBox1.Text               = "1. Choose ISO or DVD as a source"

$Form.Controls.Add($groupBox1)
#endregion groupBox1

#region radbtn1

$radbtn1                       = New-Object System.Windows.Forms.RadioButton
$System_Drawing_Point          = New-Object System.Drawing.Point
$System_Drawing_Point.X        = 25
$System_Drawing_Point.Y        = 24
$radbtn1.Location              = $System_Drawing_Point
$radbtn1.Name                  = "radbtn1"
$System_Drawing_Size           = New-Object System.Drawing.Size
$System_Drawing_Size.Height    = 30
$System_Drawing_Size.Width     = 50
$radbtn1.Size                  = $System_Drawing_Size
$radbtn1.Text                  = "ISO"


$groupBox1.Controls.Add($radbtn1)
#endregion radbtn1

#region radbtn2

$radbtn2                       = New-Object System.Windows.Forms.RadioButton
$System_Drawing_Point          = New-Object System.Drawing.Point
$System_Drawing_Point.X        = 120
$System_Drawing_Point.Y        = 24
$radbtn2.Location              = $System_Drawing_Point
$radbtn2.Name                  = "radbtn2"
$System_Drawing_Size           = New-Object System.Drawing.Size
$System_Drawing_Size.Height    = 30
$System_Drawing_Size.Width     = 50
$radbtn2.Size                  = $System_Drawing_Size
$radbtn2.Text                  = "DVD"
#$radbtn2.TabIndex             = 0

$groupBox1.Controls.Add($radbtn2)
#endregion radbtn2

#region txtSourcePath

$txtSourcePath                = New-Object System.Windows.Forms.TextBox
$System_Drawing_Point         = New-Object System.Drawing.Point
$System_Drawing_Point.X       = 25
$System_Drawing_Point.Y       = 60
$txtSourcePath.Location       = $System_Drawing_Point
$txtSourcePath.Name           = "txtSourcePath"
$System_Drawing_Size          = New-Object System.Drawing.Size
$System_Drawing_Size.Height   = 25
$System_Drawing_Size.Width    = 418
$txtSourcePath.Size           = $System_Drawing_Size


$groupBox1.Controls.Add($txtSourcePath)
#endregion txtSourcePath

#region ISO

$ISO                          = New-Object System.Windows.Forms.Button
$System_Drawing_Point         = New-Object System.Drawing.Point
$System_Drawing_Point.X       = 460
$System_Drawing_Point.Y       = 156
$ISO.Location                 = $System_Drawing_Point
$ISO.Name                     = "ISO"
$System_Drawing_Size          = New-Object System.Drawing.Size
$System_Drawing_Size.Height   = 25
$System_Drawing_Size.Width    = 35
$ISO.Size                     = $System_Drawing_Size
$ISO.TabIndex                 = 0
$ISO.Text                     = "..."
$ISO.UseVisualStyleBackColor  = $True
$ISO.Font=$font

$groupBox1.Controls.Add($ISO)
#endregion ISO

#region groupBox2

$groupBox2                    = New-Object System.Windows.Forms.GroupBox
$System_Drawing_Point         = New-Object System.Drawing.Point
$System_Drawing_Point.X       = 5
$System_Drawing_Point.Y       = 210
$groupBox2.Location           = $System_Drawing_Point
$groupBox2.Name               = "groupBox2"
$System_Drawing_Size          = New-Object System.Drawing.Size
$System_Drawing_Size.Height   = 60
$System_Drawing_Size.Width    = 450
$groupBox2.Size               = $System_Drawing_Size
$groupBox2.Text               = "2. Select an OS Edition"

$Form.Controls.Add($groupBox2)
#endregion groupBox2

#region cmbSkuList

$cmbSkuList                   = New-Object System.Windows.Forms.ComboBox
$cmbSkuList.FormattingEnabled = $True
$cmbSkuList.Items.Add("FOUNDATION") | Out-Null
$cmbSkuList.Items.Add("WEB") | Out-Null
$cmbSkuList.Items.Add("STANDARD")  | Out-Null
$cmbSkuList.Items.Add("ENTERPRISE") | Out-Null
$cmbSkuList.Items.Add("DATACENTER") | Out-Null
$System_Drawing_Point         = New-Object System.Drawing.Point
$System_Drawing_Point.X       = 25
$System_Drawing_Point.Y       = 25
$cmbSkuList.Location          = $System_Drawing_Point
$cmbSkuList.Name              = "cmbVhdFormat"
$System_Drawing_Size          = New-Object System.Drawing.Size
$System_Drawing_Size.Height   = 25
$System_Drawing_Size.Width    = 418
$cmbSkuList.Size              = $System_Drawing_Size


$groupBox2.Controls.Add($cmbSkuList)
#endregion cmbSkuList

#region groupBox3

$groupBox3                    = New-Object System.Windows.Forms.GroupBox
$System_Drawing_Point         = New-Object System.Drawing.Point
$System_Drawing_Point.X       = 5
$System_Drawing_Point.Y       = 280
$groupBox3.Location           = $System_Drawing_Point
$groupBox3.Name               = "groupBox3"
$System_Drawing_Size          = New-Object System.Drawing.Size
$System_Drawing_Size.Height   = 60
$System_Drawing_Size.Width    = 450
$groupBox3.Size               = $System_Drawing_Size
$groupBox3.Text               = "3. Choose a destination drive to store the ISO"
$Form.Controls.Add($groupBox3)
#endregion groupBox2

#region txtDestPath

$txtDestPath                  = New-Object System.Windows.Forms.TextBox
$System_Drawing_Point         = New-Object System.Drawing.Point
$System_Drawing_Point.X       = 25
$System_Drawing_Point.Y       = 24
$txtDestPath.Location         = $System_Drawing_Point
$txtDestPath.Name             = "txtDestPath"
$System_Drawing_Size          = New-Object System.Drawing.Size
$System_Drawing_Size.Height   = 25
$System_Drawing_Size.Width    = 418
$txtDestPath.Size             = $System_Drawing_Size

$groupBox3.Controls.Add($txtDestPath)
#endregion txtDestPath

#region Destbtn

$Destbtn                         = New-Object System.Windows.Forms.Button
$System_Drawing_Point            = New-Object System.Drawing.Point
$System_Drawing_Point.X          = 460
$System_Drawing_Point.Y          = 302
$Destbtn.Location                = $System_Drawing_Point
$Destbtn.Name                    = "Destbtn"
$System_Drawing_Size             = New-Object System.Drawing.Size
$System_Drawing_Size.Height      = 24
$System_Drawing_Size.Width       = 35
$Destbtn.Size                    = $System_Drawing_Size
$Destbtn.Text                    = "..."
$Destbtn.UseVisualStyleBackColor = $True
$Destbtn.Font=$font
$groupBox3.Controls.Add($Destbtn)
#endregion Destbtn

#region groupBox4

$groupBox4                    = New-Object System.Windows.Forms.GroupBox
$System_Drawing_Point         = New-Object System.Drawing.Point
$System_Drawing_Point.X       = 5
$System_Drawing_Point.Y       = 350
$groupBox4.Location           = $System_Drawing_Point
$groupBox4.Name               = "groupBox4"
$System_Drawing_Size          = New-Object System.Drawing.Size
$System_Drawing_Size.Height   = 60
$System_Drawing_Size.Width    = 450
$groupBox4.Size               = $System_Drawing_Size
$groupBox4.Text               = "4. Choose a custom driver to inject into the ISO"
$Form.Controls.Add($groupBox4)
#endregion groupBox4

#region CheckBox

$chkbox                       = New-Object System.Windows.Forms.CheckBox
$System_Drawing_Point         = New-Object System.Drawing.Point
$System_Drawing_Point.X       = 25
$System_Drawing_Point.Y       = 24
$chkbox.Location              = $System_Drawing_Point
$chkbox.Name                  = "chkbox"
$System_Drawing_Size          = New-Object System.Drawing.Size
$System_Drawing_Size.Height   = 20
$System_Drawing_Size.Width    = 20
$chkbox.Size                  = $System_Drawing_Size
$groupBox4.Controls.Add($chkbox)
#endregion chkbox

#region textCustomPath

$txtcstmPath                  = New-Object System.Windows.Forms.TextBox
$System_Drawing_Point         = New-Object System.Drawing.Point
$System_Drawing_Point.X       = 50
$System_Drawing_Point.Y       = 24
$txtcstmPath.Location         = $System_Drawing_Point
$txtcstmPath.Name             = "txtcstmPath"
$System_Drawing_Size          = New-Object System.Drawing.Size
$System_Drawing_Size.Height   = 25
$System_Drawing_Size.Width    = 392
$txtcstmPath.Size             = $System_Drawing_Size
$groupBox4.Controls.Add($txtcstmPath)
#endregion txtcstmPath

#region custDrvbtn

$custDrvbtn                         = New-Object System.Windows.Forms.Button
$System_Drawing_Point               = New-Object System.Drawing.Point
$System_Drawing_Point.X             = 460
$System_Drawing_Point.Y             = 372
$custDrvbtn.Location                = $System_Drawing_Point
$custDrvbtn.Name                    = "custDrvbtn"
$System_Drawing_Size                = New-Object System.Drawing.Size
$System_Drawing_Size.Height         = 24
$System_Drawing_Size.Width          = 35
$custDrvbtn.Size                    = $System_Drawing_Size
$custDrvbtn.Text                    = "..."
$custDrvbtn.UseVisualStyleBackColor = $True
$custDrvbtn.Font=$font
$groupBox4.Controls.Add($custDrvbtn)
#endregion custDrvbtn

$START = New-Object System.Windows.Forms.Button
$START.Location = New-Object System.Drawing.Size(30, 430)
$START.Size = New-Object System.Drawing.Size(418, 50)
$START.Text = "START"
$START.BackColor="DarkGray"
$START.ForeColor= "Black"
$START.Font=$font

### add click button functionality for ISO ###
$ISO.Add_Click({
$global:file_name=''

        if ($radbtn1.Checked){
           [void][System.Reflection.Assembly]::LoadWithPartialName("System.windows.forms")
           $SaveFileDialog = New-Object System.Windows.Forms.OpenFileDialog
           $SaveFileDialog.Title = "Select a source ISO file..."
           $SaveFileDialog.Filter = "ISO files (*.iso)|*.iso"
   
           $SaveFileDialog.initialDirectory = "C:"
            $destination = "C:\"
    

            if ($SaveFileDialog.ShowDialog() -eq [System.Windows.Forms.DialogResult]::OK)
                { 
                $global:file_name = $SaveFileDialog.FileName
                Write-Host "$global:file_name"}
            $txtSourcePath.Text = "$global:file_name"
        }
        elseif ($radbtn2.Checked){

            [void][System.Reflection.Assembly]::LoadWithPartialName("System.windows.forms")
            $foldername = New-Object System.Windows.Forms.FolderBrowserDialog
            $foldername.Description = "Select a DVD Drive as a source..."
            $foldername.rootfolder = "MyComputer"

            if($foldername.ShowDialog() -eq "OK")
            {
                $folder = ''
                $global:file_name = $foldername.SelectedPath
                Write-Host "$global:file_name"
            }
            $txtSourcePath.Text = "$global:file_name"
        }
        else{
        [System.Windows.Forms.MessageBox]::Show(" Please select either ISO or DVD and select the path ")
        }
        
 })

### destunation Butoon onClick functionality ###  
$Destbtn.Add_Click({
$global:ISOFile=''

$ISO_loc = New-Object System.Windows.Forms.FolderBrowserDialog
        $ISO_loc.rootfolder = "MyComputer"
        $ISO_loc.Description = "Choose a destination drive/folder to store Final ISO"
        if($ISO_loc.ShowDialog() -eq "OK")
        {
            $ISO_folder = ''
            if($ISO_loc.SelectedPath.EndsWith("\")){
                $ISO_folder += $ISO_loc.SelectedPath
                $global:ISOFile=$ISO_folder
                $global:ISOFile+="WS08R2SP1_New.iso"
            }
            else{
                $ISO_folder += $ISO_loc.SelectedPath
                $global:ISOFile="$ISO_folder\WS08R2SP1_New.iso"
                Write-Host "$ISO_folder"
            }
            if($global:ISOFile.Equals(''))
            {
            $global:ISOFile = "$path\WS08R2SP1_New.iso"
            }
        }
        else
        {
        $global:ISOFile = "$path\WS08R2SP1_New.iso"
        }
        $txtDestPath.Text= "$global:ISOFile"
})

$custDrvbtn.Add_Click({

       if($chkbox.Checked){
            $custDrvPath = New-Object System.Windows.Forms.FolderBrowserDialog
            $custDrvPath.rootfolder = "MyComputer"
            $custDrvPath.Description = "Choose the custom driver injection path/folder"
            if($custDrvPath.ShowDialog() -eq "OK")
            {
            $global:Cust_folder = ''
            $global:Cust_folder += $custDrvPath.SelectedPath
          
            Write-Host "$global:Cust_folder"
            
            ## display selected Drive or folder to text box 
            $txtcstmPath.Text = $global:Cust_folder
            } else {
                [System.Windows.Forms.MessageBox]::Show("Please select folder from which you want to inject custom drivers other than USB3.0") 
            }
        }
}) 

$START.Add_Click({
        
        if($global:ISOFile -eq ''){   
            $global:ISOFile = "$path\WS08R2SP1_New.iso"
            $txtDestPath.Text= $global:ISOFile
            Write-Host "global iso file is $global:ISOFile"
        }
        
    ############### ensuring diff checks ##### 
    if(($cmbSkuList.SelectedItem -ne $NULL) -and (($radbtn1.Checked -eq 1) -or ($radbtn2.Checked -eq 1)) `
        -and ($global:ISOfile  -ne $NULL) -and ($global:file_name -ne $NULL) -and (!($chkbox.checked) `
        -or (($chkbox.checked) -and ($global:Cust_folder -ne $NULL)))) 
    {
    
                    $SKU_select= $cmbSkuList.SelectedItem.ToString()
                    Write-Host "SKU selected is $SKU_select"
                    if ($SKU_select -eq "STANDARD"){
                    $a=1
                    }
                    elseif($SKU_select -eq "ENTERPRISE"){
                    $a=3
                    }
                    elseif($SKU_select -eq "DATACENTER"){
                    $a=5
                    }
					elseif($SKU_select -eq "FOUNDATION"){
                    $a=1
                    }
                    else {
                    $a=7
                    }
                Write-Host "Value of a = $a "

        #################Driver Injection on the ISO image
        Write-Host "$global:file_name"
        if($global:file_name.EndsWith(".iso") -or $global:file_name.EndsWith(".ISO")){
                if (-not(test-path "$path\tools\7zip\7z.exe")){ throw "\tools\7zip\7z.exe is missing"}
                set-alias sz "$path\tools\7zip\7z.exe"
                sz x -y "-o$extractedDisk" "$global:file_name"
                Write-Host "Extraction Complete"
                        
                Get-ChildItem $extractedDisk -Recurse |
                Where-Object {$_.GetType().ToString() -eq "System.IO.FileInfo"} |
                Set-ItemProperty -Name IsReadOnly -Value $false

                $bi=2 ##for boot.wim index
                $i = 1
                $x = 1
                while ($i -le $bi)
                {
                    Write-Host
                    Write-Host "   INFO: Processing image with boot.wim index = $i "
                    ### Attempt to mount                   
                    try
                    {
                        $text1 = "INFO: Attempting to Mount dism.exe /get-wimInfo /wimfile:$extractedDisk\sources\boot.wim for index $i"
                        $textBox1.AppendText($Text1)
                        $Text2 = dism.exe /mount-Wim /WimFile:$extractedDisk\sources\boot.wim /Index:"$i" /MountDir:$wimPath  | Out-String
                        $textBox1.AppendText($Text2)
                        $text3 = "   INFO: dism mount succeeded"
                        $textBox1.AppendText($Text3)
                    }
                    catch
                    {
                        $text1 = "INFO: Mount-WindowsImage was attempted but failed`
                                  Failed to mount /WimFile:$extractedDisk\sources\boot.wim to location `
                                  /MountDir:$wimPath using index $i Please check that `
                                  /WimFile:$extractedDisk\sources\boot.wim and the mount directory /MountDir:$wimPath exist"
                    }

                    ### get mounted wiminfo
                    try
                    {
                        $text1 = "INFO: Attempting to get dism.exe /get-MountedwimInfo"
                        $textBox1.AppendText($text1)
                        $Text2 = dism.exe /get-mountedwimInfo | Out-String
                        $textBox1.AppendText($Text2)
                    }
                    catch
                    {
                        $text1 = "INFO: failed to get mounted wim info`
                                  Please check that mount directory /MountDir:$wimPath exist"
                    }

                    ### Add drivers
                    try
                    {
                        $text1 = "INFO: Attempting to add Drivers to /wimfile:$extractedDisk\sources\boot.wim of index $i"
                        $textBox1.AppendText($text1)
                        $Text2 = dism.exe /image:$wimPath /Add-Driver /Driver:$driverPath /Recurse | Out-String
                        $textBox1.AppendText($text2)
                        
                         if(($chkbox.checked) -and ($txtcstmPath -ne $null)){
                        $text4 = dism.exe /image:$wimPath /Add-Driver /Driver:$global:Cust_folder /Recurse | Out-String
                        $textBox1.AppendText($text4)
                        }
                        
                        $text3 = "   INFO: Drivers added successfully"
                        $textBox1.AppendText($text3)
                    }
                    catch
                    {
                        $text1 = "INFO: /Add-Drivers was attempted and failed`
                                  Please check that Driver path /Driver:$driverPath exist"
                    }

                    ### commit wim
                    try
                    {
                        $text1 = "INFO: Attempting commit wim to /wimfile:$extractedDisk\sources\boot.wim of index $i"
                        $textBox1.AppendText($text1)
                        $Text2 = dism.exe /Commit-Wim /MountDir:$wimPath | Out-String
                        $textBox1.AppendText($Text2)
                        $text3 = "   INFO: wim commit successfull"
                        $textBox1.AppendText($text3)
                    }
                    catch
                    {
                        $text1 = "INFO: /Wim-Commit was attempted and failed`
                                  Please check that /MountDir:$wimPath exist and not open in explorer"
                    }

                    ### unmount WIM
                    try
    		        {
                        $count = 1
    			        while(((Get-ChildItem -Force $wimPath) -ne $Null) -and ($count -lt 5))
                        {
                                                       
                                $Text1 = "   INFO: Attempting Unmount-Wim -Path $wimPath "
                                $textBox1.AppendText($Text1)
        			            $Text2 = dism.exe /Unmount-Wim /MountDir:$wimPath /Discard | Out-String
                                $textBox1.AppendText($Text2)			        
                                $Text3 = dism.exe /cleanup-wim | Out-String
                                $textBox1.AppendText($Text3)
                                Start-sleep -Seconds 10
                                $count=$count + 1
                            
                        }		        
                        $text4 = "   INFO: Dismount-WindowsImage for index ($i) succeeded"
                        $textBox1.AppendText($text4)
                    }
    		        catch
                    {
                        
    			        $Text1 = "`n   ERROR: Dismount-WindowsImage with the -Save option was attempted but failed `n
    			        Please check that $extractedDisk\sources\boot.wim and the mount directory $wimPah exist`
    			        Cleanup: clean $wimPah using the Dism tool with the /Unmount-Wim and/or /Cleanup-Wim options`
    			        (note: ensure that there are no Windows Explorer windows open for the mount directory)`
    			        Example 1: dism /Unmount-Wim /mountdir:$wimPath /discard`
    			        Example 2: dism /Cleanup-Wim After the mount dir has been successfully cleaned up with Dism, `
                        use Windows Explorer to delete it.Use dism /Get-MountedWimInfo to verify that all mounted `
                        images have been cleaned up successfully.`n"
                        $textBox1.AppendText($Text1)
    			        throw
                    }
                    if($count -ge 5){
                        break;
                    }
                    else{
                        $i = $i + 1
                    }
                }
                
                if($count -lt 5)
                {    
                    $x=1
                    $ii=2
                    ### mount, inject, save and unmount operaions for install.wim
                    while ($x -le $ii)
                    {
                        Write-Host
                        Write-Host " INFO: Processing image with install.wim index = $a "
                        ### Attempt to mount                  
                        try
                        {
                            $text1 = "INFO: Attempting to Mount dism.exe /get-wimInfo /wimfile:$extractedDisk\sources\install.wim for index $a"
                            $textBox1.AppendText($Text1)
                            $Text2 = dism.exe /mount-Wim /WimFile:$extractedDisk\sources\install.wim /Index:"$a" /MountDir:$installWimPath  | Out-String
                            $textBox1.AppendText($Text2)
                            $text3 = "   INFO: dism mount succeeded"
                            $textBox1.AppendText($Text3)
                        }
                        catch
                        {
                            $text1 = "INFO: Mount-WindowsImage was attempted but failed`
                                      Failed to mount /WimFile:$extractedDisk\sources\install.wim to location `
                                      /MountDir:$installWimPath using index $a Please check that `
                                      /WimFile:$extractedDisk\sources\install.wim and the mount directory /MountDir:$installWimPath exist"
                        }

                        ### get mounted wiminfo
                        try
                        {
                            $text1 = "INFO: Attempting to get dism.exe /get-MountedwimInfo"
                            $textBox1.AppendText($text1)
                            $Text2 = dism.exe /get-mountedwimInfo | Out-String
                            $textBox1.AppendText($Text2)
                        }
                        catch
                        {
                            $text1 = "INFO: failed to get mounted wim info`
                                      Please check that mount directory /MountDir:$installWimPath exist"
                            $textBox1.AppendText($text1)
                        }

                        ### Add drivers
                        try
                        {
                            $text1 = "INFO: Attempting to add Drivers to /wimfile:$extractedDisk\sources\install.wim of index $a"
                            $textBox1.AppendText($text1)
                            $Text2 = dism.exe /image:$installWimPath /Add-Driver /Driver:$driverPath /Recurse | Out-String
                            $textBox1.AppendText($Text2)
                            
                             if(($chkbox.checked) -and ($txtcstmPath -ne $null)){
                            $text4 = dism.exe /image:$installWimPath /Add-Driver /Driver:$global:Cust_folder /Recurse | Out-String
                            $textBox1.AppendText($text4)
                            }
                            
                            $text3 = "   INFO: Drivers added successfully"
                            $textBox1.AppendText($text3)
                        }
                        catch
                        {
                            $text1 = "INFO: /Add-Drivers was attempted and failed`
                                      Please check that Driver path /Driver:$installWimPath exist"
                            $textBox1.AppendText($text1)
                        }

                        ### commit wim
                        try
                        {
                            $text1 = "INFO: Attempting commit wim to /wimfile:$extractedDisk\sources\install.wim of index $a"
                            $textBox1.AppendText($text1)
                            $Text2 = dism.exe /Commit-Wim /MountDir:$installWimPath | Out-String
                            $textBox1.AppendText($Text2)
                            $text3 = "   INFO: wim commit successfull"
                            $textBox1.AppendText($text3)
                        }
                        catch
                        {
                            $text1 = "INFO: /Wim-Commit was attempted and failed`
                                      Please check that /MountDir:$installWimPath exist and not open in explorer"
                            $textBox1.AppendText($text1)
                        }

                        ### unmount WIM
                        try
        		        {
                            $count=1
        			        while(((Get-ChildItem -Force $installWimPath) -ne $Null) -and ($count -lt 5))
                            {
                                
                                $Text1 = "   INFO: Attempting Unmount-Wim -Path $installWimPath "
                                $textBox1.AppendText($Text1)
        			            $Text2 = dism.exe /Unmount-Wim /MountDir:$installWimPath /Discard | Out-String
                                $textBox1.AppendText($Text2)
                                Write-Host "... waiting to unmount the image"
                                Start-sleep -Seconds 10			        
                                $Text3 = dism.exe /cleanup-wim | Out-String
                                $textBox1.AppendText($Text3)
                                Write-Host "Unmount complete"
                                Start-sleep -Seconds 10
                                $count = $count+1
                            }		        
                            $text4 = "   INFO: Dismount-WindowsImage for index ($a) succeeded"
                            $textBox1.AppendText($text4)
                        }
        		        catch
                        {
                            
        			        $Text1 = "`n   ERROR: Dismount-WindowsImage with the -Save option was attempted but failed `n
        			        Please check that $extractedDisk\sources\boot.wim and the mount directory $installWimPath exist`
        			        Cleanup: clean $installWimPath using the Dism tool with the /Unmount-Wim and/or /Cleanup-Wim options`
        			        (note: ensure that there are no Windows Explorer windows open for the mount directory)`
        			        Example 1: dism /Unmount-Wim /mountdir:$installWimPath /discard`
        			        Example 2: dism /Cleanup-Wim After the mount dir has been successfully cleaned up with Dism, `
                            use Windows Explorer to delete it.Use dism /Get-MountedWimInfo to verify that all mounted `
                            images have been cleaned up successfully.`n"
                            $textBox1.AppendText($Text1)
        			        throw
                        }
                        if($SKU_select -eq "FOUNDATION")
    					{ 
    						break
    					} elseif($count -ge 5) {
                            break
                        }
                        else{
    						$a = $a + 1
    						$x=$x+1
    					}
                    }
                }  
                  
                if($count -ge 5){
                
                    [System.Windows.Forms.MessageBox]::Show(" Driver Injection Failed !!!!!!!")
                    $Text1 = "INFO:Image creation failed!!! Copy the tool to a different location and retry "
                    $textBox1.AppendText($Text1)
                }
                else{
                    ### Create an ISO file ###
                    $BootData='2#p0,e,b"{0}"#pEF,e,b"{1}"' -f "$extractedDisk\boot\etfsboot.com","$extractedDisk\efi\Microsoft\boot\efisys.bin"  
                
                    $Proc = Start-Process -FilePath "$PathToOscdimg\oscdimg.exe" -ArgumentList @("-bootdata:$BootData",'-u2','-udfver102',"$extractedDisk","$global:ISOFile") -PassThru -Wait -NoNewWindow
                
                    if($Proc.ExitCode -ne 0)
                    {
                        Throw "Failed to generate ISO with exitcode: $($Proc.ExitCode)"
                    }
                    else
                    {
                    Write-Host "ISO creation successful"
                    }
                    
                        Remove-Item -Path $destDir -Recurse -Force
                    
                }
        }
        else{
        ###########Injection of Drivers on DVD image
            Write-Host "COPYING INITIATED"
                Copy-Item "$global:file_name\*" $extractedDisk -recurse |Out-Null
                Write-Host "Copying Over"
            
                Get-ChildItem $extractedDisk -Recurse |
                Where-Object {$_.GetType().ToString() -eq "System.IO.FileInfo"} |
                Set-ItemProperty -Name IsReadOnly -Value $false
        
        
               $bi=2 ##for boot.wim index
                $i = 1
                $x = 1
                while ($i -le $bi)
                {
                    Write-Host
                    Write-Host "   INFO: Processing image with boot.wim index = $i "
                    ### Attempt to mount                   
                    try
                    {
                        $text1 = "INFO: Attempting to Mount dism.exe /get-wimInfo /wimfile:$extractedDisk\sources\boot.wim for index $i"
                        $textBox1.AppendText($Text1)
                        $Text2 = dism.exe /mount-Wim /WimFile:$extractedDisk\sources\boot.wim /Index:"$i" /MountDir:$wimPath  | Out-String
                        $textBox1.AppendText($Text2)
                        $text3 = "   INFO: dism mount succeeded"
                        $textBox1.AppendText($Text3)
                    }
                    catch
                    {
                        $text1 = "INFO: Mount-WindowsImage was attempted but failed`
                                  Failed to mount /WimFile:$extractedDisk\sources\boot.wim to location `
                                  /MountDir:$wimPath using index $i Please check that `
                                  /WimFile:$extractedDisk\sources\boot.wim and the mount directory /MountDir:$wimPath exist"
                    }

                    ### get mounted wiminfo
                    try
                    {
                        $text1 = "INFO: Attempting to get dism.exe /get-MountedwimInfo"
                        $textBox1.AppendText($text1)
                        $Text2 = dism.exe /get-mountedwimInfo | Out-String
                        $textBox1.AppendText($Text2)
                    }
                    catch
                    {
                        $text1 = "INFO: failed to get mounted wim info`
                                  Please check that mount directory /MountDir:$wimPath exist"
                    }

                    ### Add drivers
                    try
                    {
                        $text1 = "INFO: Attempting to add Drivers to /wimfile:$extractedDisk\sources\boot.wim of index $i"
                        $textBox1.AppendText($text1)
                        $Text2 = dism.exe /image:$wimPath /Add-Driver /Driver:$driverPath /Recurse | Out-String
                        $textBox1.AppendText($text2)
                        
                         if(($chkbox.checked) -and ($txtcstmPath -ne $null)){
                        $text4 = dism.exe /image:$wimPath /Add-Driver /Driver:$global:Cust_folder /Recurse | Out-String
                        $textBox1.AppendText($text4)
                        }
                        
                        $text3 = "   INFO: Drivers added successfully"
                        $textBox1.AppendText($text3)
                    }
                    catch
                    {
                        $text1 = "INFO: /Add-Drivers was attempted and failed`
                                  Please check that Driver path /Driver:$driverPath exist"
                    }

                    ### commit wim
                    try
                    {
                        $text1 = "INFO: Attempting commit wim to /wimfile:$extractedDisk\sources\boot.wim of index $i"
                        $textBox1.AppendText($text1)
                        $Text2 = dism.exe /Commit-Wim /MountDir:$wimPath | Out-String
                        $textBox1.AppendText($Text2)
                        $text3 = "   INFO: wim commit successfull"
                        $textBox1.AppendText($text3)
                    }
                    catch
                    {
                        $text1 = "INFO: /Wim-Commit was attempted and failed`
                                  Please check that /MountDir:$wimPath exist and not open in explorer"
                    }

                    ### unmount WIM
                    try
    		        {
                        $count=1
    			        while(((Get-ChildItem -Force $wimPath) -ne $Null) -and ($count -lt 5))
                        {
                                                       
                                $Text1 = "   INFO: Attempting Unmount-Wim -Path $wimPath "
                                $textBox1.AppendText($Text1)
        			            $Text2 = dism.exe /Unmount-Wim /MountDir:$wimPath /Discard | Out-String
                                $textBox1.AppendText($Text2)			        
                                $Text3 = dism.exe /cleanup-wim | Out-String
                                $textBox1.AppendText($Text3)
                                Start-sleep -Seconds 10
                                $count=$count + 1
                            
                        }		        
                        $text4 = "   INFO: Dismount-WindowsImage for index ($i) succeeded"
                        $textBox1.AppendText($text4)
                    }
    		        catch
                    {
                        
    			        $Text1 = "`n   ERROR: Dismount-WindowsImage with the -Save option was attempted but failed `n
    			        Please check that $extractedDisk\sources\boot.wim and the mount directory $wimPah exist`
    			        Cleanup: clean $wimPah using the Dism tool with the /Unmount-Wim and/or /Cleanup-Wim options`
    			        (note: ensure that there are no Windows Explorer windows open for the mount directory)`
    			        Example 1: dism /Unmount-Wim /mountdir:$wimPath /discard`
    			        Example 2: dism /Cleanup-Wim After the mount dir has been successfully cleaned up with Dism, `
                        use Windows Explorer to delete it.Use dism /Get-MountedWimInfo to verify that all mounted `
                        images have been cleaned up successfully.`n"
                        $textBox1.AppendText($Text1)
    			        throw
                    }
                    if($count -ge 5){
                        break;
                    }
                    else{
                        $i = $i + 1
                    }
                }
                
                if($count -lt 5)
                {    
                    $x=1
                    $ii=2
                    ### mount, inject, save and unmount operaions for install.wim
                    while ($x -le $ii)
                    {
                        Write-Host
                        Write-Host " INFO: Processing image with install.wim index = $a "
                        ### Attempt to mount                  
                        try
                        {
                            $text1 = "INFO: Attempting to Mount dism.exe /get-wimInfo /wimfile:$extractedDisk\sources\install.wim for index $a"
                            $textBox1.AppendText($Text1)
                            $Text2 = dism.exe /mount-Wim /WimFile:$extractedDisk\sources\install.wim /Index:"$a" /MountDir:$installWimPath  | Out-String
                            $textBox1.AppendText($Text2)
                            $text3 = "   INFO: dism mount succeeded"
                            $textBox1.AppendText($Text3)
                        }
                        catch
                        {
                            $text1 = "INFO: Mount-WindowsImage was attempted but failed`
                                      Failed to mount /WimFile:$extractedDisk\sources\install.wim to location `
                                      /MountDir:$installWimPath using index $a Please check that `
                                      /WimFile:$extractedDisk\sources\install.wim and the mount directory /MountDir:$installWimPath exist"
                        }

                        ### get mounted wiminfo
                        try
                        {
                            $text1 = "INFO: Attempting to get dism.exe /get-MountedwimInfo"
                            $textBox1.AppendText($text1)
                            $Text2 = dism.exe /get-mountedwimInfo | Out-String
                            $textBox1.AppendText($Text2)
                        }
                        catch
                        {
                            $text1 = "INFO: failed to get mounted wim info`
                                      Please check that mount directory /MountDir:$installWimPath exist"
                            $textBox1.AppendText($text1)
                        }

                        ### Add drivers
                        try
                        {
                            $text1 = "INFO: Attempting to add Drivers to /wimfile:$extractedDisk\sources\install.wim of index $a"
                            $textBox1.AppendText($text1)
                            $Text2 = dism.exe /image:$installWimPath /Add-Driver /Driver:$driverPath /Recurse | Out-String
                            $textBox1.AppendText($Text2)
                            
                             if(($chkbox.checked) -and ($txtcstmPath -ne $null)){
                            $text4 = dism.exe /image:$installWimPath /Add-Driver /Driver:$global:Cust_folder /Recurse | Out-String
                            $textBox1.AppendText($text4)
                            }
                            
                            $text3 = "   INFO: Drivers added successfully"
                            $textBox1.AppendText($text3)
                        }
                        catch
                        {
                            $text1 = "INFO: /Add-Drivers was attempted and failed`
                                      Please check that Driver path /Driver:$installWimPath exist"
                            $textBox1.AppendText($text1)
                        }

                        ### commit wim
                        try
                        {
                            $text1 = "INFO: Attempting commit wim to /wimfile:$extractedDisk\sources\install.wim of index $a"
                            $textBox1.AppendText($text1)
                            $Text2 = dism.exe /Commit-Wim /MountDir:$installWimPath | Out-String
                            $textBox1.AppendText($Text2)
                            $text3 = "   INFO: wim commit successfull"
                            $textBox1.AppendText($text3)
                        }
                        catch
                        {
                            $text1 = "INFO: /Wim-Commit was attempted and failed`
                                      Please check that /MountDir:$installWimPath exist and not open in explorer"
                            $textBox1.AppendText($text1)
                        }

                        ### unmount WIM
                        try
        		        {
                            $count=1
        			        while(((Get-ChildItem -Force $installWimPath) -ne $Null) -and ($count -lt 5))
                            {
                                
                                $Text1 = "   INFO: Attempting Unmount-Wim -Path $installWimPath "
                                $textBox1.AppendText($Text1)
        			            $Text2 = dism.exe /Unmount-Wim /MountDir:$installWimPath /Discard | Out-String
                                $textBox1.AppendText($Text2)
                                Write-Host "... waiting to unmount the image"
                                Start-sleep -Seconds 10			        
                                $Text3 = dism.exe /cleanup-wim | Out-String
                                $textBox1.AppendText($Text3)
                                Write-Host "Unmount complete"
                                Start-sleep -Seconds 10
                                $count = $count+1
                            }		        
                            $text4 = "   INFO: Dismount-WindowsImage for index ($a) succeeded"
                            $textBox1.AppendText($text4)
                        }
        		        catch
                        {
                            
        			        $Text1 = "`n   ERROR: Dismount-WindowsImage with the -Save option was attempted but failed `n
        			        Please check that $extractedDisk\sources\boot.wim and the mount directory $installWimPath exist`
        			        Cleanup: clean $installWimPath using the Dism tool with the /Unmount-Wim and/or /Cleanup-Wim options`
        			        (note: ensure that there are no Windows Explorer windows open for the mount directory)`
        			        Example 1: dism /Unmount-Wim /mountdir:$installWimPath /discard`
        			        Example 2: dism /Cleanup-Wim After the mount dir has been successfully cleaned up with Dism, `
                            use Windows Explorer to delete it.Use dism /Get-MountedWimInfo to verify that all mounted `
                            images have been cleaned up successfully.`n"
                            $textBox1.AppendText($Text1)
        			        throw
                        }
                        if($SKU_select -eq "FOUNDATION")
    					{ 
    						break
    					} elseif($count -ge 5) {
                            break
                        }
                        else{
    						$a = $a + 1
    						$x=$x+1
    					}
                    }
                }  
                  
                if($count -ge 5){
                
                    [System.Windows.Forms.MessageBox]::Show(" Driver Injection Failed !!!!!!!")
                    $Text1 = "INFO:Image creation failed!!! Copy the tool to a different location and retry "
                    $textBox1.AppendText($Text1)
                }
                else{
                        ### Create an ISO file ###
                        $BootData='2#p0,e,b"{0}"#pEF,e,b"{1}"' -f "$extractedDisk\boot\etfsboot.com","$extractedDisk\efi\Microsoft\boot\efisys.bin"  
                
                        $Proc = Start-Process -FilePath "$PathToOscdimg\oscdimg.exe" -ArgumentList @("-bootdata:$BootData",'-u2','-udfver102',"$extractedDisk","$global:ISOFile") -PassThru -Wait -NoNewWindow
                
                        if($Proc.ExitCode -ne 0)
                        {
                            Throw "Failed to generate ISO with exitcode: $($Proc.ExitCode)"
                        }
                        else
                        {
                        Write-Host "ISO creation successful"
                        }
                    
                            Remove-Item -Path $destDir -Recurse -Force
                    
                  }
            }
        
     }
     else {
     
            if(($radbtn1.Checked -eq 0) -and ($radbtn2.Checked -eq 0)){
                [System.Windows.Forms.MessageBox]::Show(" Please select either ISO or DVD and then press start")
            } 
            
            if($txtSourcePath.Text -eq '') {
             [System.Windows.Forms.MessageBox]::Show(" Please choose the input source for either ISO or DVD and then press start ")
            }
            
            if ($global:ISOfile  -eq '') {
             [System.Windows.Forms.MessageBox]::Show(" Please choose the destination ISO path and then press start ")
            }            
            
            ############# SKU selection ##################### 
            if($cmbSkuList.SelectedItem -eq $NULL) {
            [System.Windows.Forms.MessageBox]::Show("Please select one OS edition and then press start ")
            }      
                                  
            if(($chkbox.checked) -and ($global:Cust_folder -eq '')){
            [System.Windows.Forms.MessageBox]::Show("Please select the custom driver path and then press start ")
            }            
         }
})

$Form.Controls.Add($ISO)

$Form.Controls.Add($Destbtn)
$Form.Controls.Add($custDrvbtn)
$Form.Controls.Add($textBox1)
$Form.Controls.Add($Label)
$Form.Controls.Add($START)

$InitialFormWindowState = New-Object System.Windows.Forms.FormWindowState

$Form.AutoSize = $true

$Form.KeyPreview = $True
$Form.Add_KeyDown({if ($_.KeyCode -eq "Enter") 
    {$x=$objTextBox.Text;$Form.Close()}})
$Form.Add_KeyDown({if ($_.KeyCode -eq "Escape") 
    {$Form.Close()}})
    
    $textBox1.BackColor= 'BLACK'
    $textBox1.ForeColor= 'LightBlue'
    

$Form.Add_Shown({$Form.Activate()})
[void] $Form.ShowDialog()