PEBuilder and WinPE Rescue V 3.0.0.0

Just the other week i posted a new tool to build a my PE image and just as I promised in that post I created a better build and more customizable version of that tool. below is the code that makes up PEBuilder, The new version is built in PowerShell and offer options to do do things like Download and install the required ADK files, Build a image and burn it to a USB drive or mount a already created image. The idea behind PEBuilder was to give a broad yet flexible set of tools that allow the user to build there own version of WinPE. At this time the source files provided will allow you build my own version of WinPE with some other changes compared to my old version I posted quite sometime ago. Even though it is setup to use my own configuration you can easily modify the files I provided to suite your own needs, just use my source files as templates.

The Changes made to WinPE_RescueImage are as follows
  • Removed recuva until something can be found that will work in WinPE
  • Added a PowerShell profile that will inclused functions to run the build in tools
    • To use a tool like cmtrace type Run-CmTrace
  • Added a function to backup files to a zip file archive 
    • Backup-ToZip -Target <whattobackup> -Destination <backupfile>
  • Added a function to securely wipe a drive 
    • Wipe-Drive -Drive E
  • Removed the launch batch files in place of PowerShell profile functions
  • Moved built in apps to an apps directory located on the root of the system drive
  • Added the Apply-Image command to install a windows wim file on a computer
To use PEBuilder download the PEBuilder package and unzip the content to a folder.
  1.  Open a PowerShell window as and administrator 
  2. Run PEBuilder.ps1 with the corresponding switches for your needs 
    1. I recommend you run Get-Help .\PEBuilder -Detailed before you start using PEBuilder
You can Download everything you need to use PEBuilder from HERE


<#
.SYNOPSIS
Script used to build a WinPE image

.DESCRIPTION
The script provides tools to build a WinPE image and customise it for your needs.
the script is configured to run with my own configurations but if you fallow my examples
then you can customise WinPE for your own needs

.PARAMETER PEType 
Used to set the type of WinPE image to be created

.PARAMETER PEBuildLocation
Sets where WinPE should be built at 

.PARAMETER CopyPE
Copies the required PE files to the PEBuildLocation

.PARAMETER InstallADK
Downloads and installs Windows ADK 1703 

.PARAMETER AddPowerShell
Adds the required PE components to the image for PowerShell

.PARAMETER CustomStartnet
Replaces the built in startnet.cmd file with a custom one. To specify your own startnet file 
place a file named startnet.cmd in the PE_SourceFiles\Startnet directory

.PARAMETER CustomBackground
Replace the built in bacground with your own image. Name your own image winpe.jpg and save it 
in teh PE_SourceFiles\Background

.PARAMETER CustomWinpeshl
Adds a winpeshl.ini file. Modify the file located in PE_SourceFiles to add your own commands

.PARAMETER CopyApps
Copies the applications located in the folder corisponding to the PEType to the Apps folder on the PE media 

.PARAMETER AddPSProfile
Adds a PowerShell profile to the all uses profile. File is located in PE_SourceFiles\PSProfile

.PARAMETER AddAutoRun
Adds autorun files to the image file. Files for autorun are in PE_ScourceFiles\Autorun

.PARAMETER MountPE
Mounts the specified PE image if you need to modify it after you have modified it, You do not needd
to use this with the CopyPE parameter

.PARAMETER DismountPE
Dismounts the specified PE image, You do not need to speify this if you use the CreateISO or BurnToUSB parameters

.PARAMETER CreateISO
Dismounts and saves the image then creates a ISO of the image in a specified location

.PARAMETER BurnToUSB
Dismounts and saves the image then burns the image to a specified drive

.PARAMETER DeletePE
Dismounts the image and deletes all content of the PEBuildLocation

.EXAMPLE
.\PEBuilder.ps1 -PEType amd64 -PEBuildLocation C:\WinPE_x64 -CopyPE -AddPowerShell -AddPSProfile -CopyApps -CustomStartnet -CustomBackground -CreateISO C:\WinPE_x64.iso -DeletePE
This will create copy all x64 WinPE files to C:\WinPE_x64 and add PowerShell, A PowerShellProfile, All Apps located in the Apps_x64 directory and a custom background. Then this command
will create the WinPE_x64.iso on the C drive and delete the PEBuildLocation directory.

By removeing the CreateISO and DeletePE pararmets everything above will be added but the image will stay mounted if other customisation needs to be done. 

.EXAMPLE 
.\PEBuilder.ps1 -InstallADK
Will download and install Windows ADK 1703 only

.EXAMPLE 
.\PEBuilder.ps1 -PEBuildLocation C:\WinPE -MountPE 
Will mount the PE image located in C:\WinPE

.EXAMPLE 
.\PEBuilder.ps1 -PEBuildLocation C:\WinPE -DismountPE
Will dismount the PE image located in C:\WinPE

.NOTES
Created By: Kris Gross
Contact: Krisgross@sccmtst.com
Twitter: @kmgamd
Version 2.0.0.0

.LINK
You can get updates to this script and others from here
http://www.sccmtst.com/
#>

Param(     
    [ValidateSet('amd64','x86')]     
    [string]$PEType, 
    [string]$PEBuildLocation,
    [switch]$CopyPE,
    [switch]$InstallADK,
    [switch]$AddPowerShell,
    [switch]$CustomStartnet,
    [switch]$Custombackground,
    [switch]$CustomWinpeshl,
    [switch]$CopyApps,
    [switch]$AddPSProfile,
    [switch]$AddAutoRun,
    [switch]$MountPE,
    [switch]$DismountPE,
    [string]$CreateISO,
    [string]$BurnToUSB,
    [switch]$DeletePE
    )
#Changeable variables
$SuccessColor = "Green"
$ErrorColor = "Red"
$StatusColor = "Cyan"
$StartMessage = "Building WinPE $PEType"

#DO NOT CHANGE
#================================================================
$CopyPEBat = @"
    @Echo off
    IF /I %PROCESSOR_ARCHITECTURE%==x86 (
        IF NOT "%PROCESSOR_ARCHITEW6432%"=="" (
            SET PROCESSOR_ARCHITECTURE=%PROCESSOR_ARCHITEW6432%
        )
    ) ELSE IF /I NOT %PROCESSOR_ARCHITECTURE%==amd64 (
        @echo Not implemented for PROCESSOR_ARCHITECTURE of %PROCESSOR_ARCHITECTURE%.
        @echo Using "%ProgramFiles%"
        
        SET NewPath="%ProgramFiles%"

        goto SetPath
    )

    SET regKeyPathFound=1
    SET wowRegKeyPathFound=1
    SET KitsRootRegValueName=KitsRoot10
    REG QUERY "HKLM\Software\Wow6432Node\Microsoft\Windows Kits\Installed Roots" /v %KitsRootRegValueName% 1>NUL 2>NUL || SET wowRegKeyPathFound=0
    REG QUERY "HKLM\Software\Microsoft\Windows Kits\Installed Roots" /v %KitsRootRegValueName% 1>NUL 2>NUL || SET regKeyPathFound=0
    if %wowRegKeyPathFound% EQU 0 (
    if %regKeyPathFound% EQU 0 (
        @echo KitsRoot not found, can't set common path for Deployment Tools
        goto :EOF 
    ) else (
        SET regKeyPath=HKLM\Software\Microsoft\Windows Kits\Installed Roots
    )
    ) else (
        SET regKeyPath=HKLM\Software\Wow6432Node\Microsoft\Windows Kits\Installed Roots
    )

    FOR /F "skip=2 tokens=2*" %%i IN ('REG QUERY "%regKeyPath%" /v %KitsRootRegValueName%') DO (SET KitsRoot=%%j)
    SET DandIRoot=%KitsRoot%Assessment and Deployment Kit\Deployment Tools
    SET WinPERoot=%KitsRoot%Assessment and Deployment Kit\Windows Preinstallation Environment
    SET WinPERootNoArch=%KitsRoot%Assessment and Deployment Kit\Windows Preinstallation Environment
    SET WindowsSetupRootNoArch=%KitsRoot%Assessment and Deployment Kit\Windows Setup
    SET USMTRootNoArch=%KitsRoot%Assessment and Deployment Kit\User State Migration Tool
    SET DISMRoot=%DandIRoot%\%PROCESSOR_ARCHITECTURE%\DISM
    SET BCDBootRoot=%DandIRoot%\%PROCESSOR_ARCHITECTURE%\BCDBoot
    SET ImagingRoot=%DandIRoot%\%PROCESSOR_ARCHITECTURE%\Imaging
    SET OSCDImgRoot=%DandIRoot%\%PROCESSOR_ARCHITECTURE%\Oscdimg
    SET WdsmcastRoot=%DandIRoot%\%PROCESSOR_ARCHITECTURE%\Wdsmcast
    SET HelpIndexerRoot=%DandIRoot%\HelpIndexer
    SET WSIMRoot=%DandIRoot%\WSIM
    SET ICDRoot=%KitsRoot%Assessment and Deployment Kit\Imaging and Configuration Designer\x86
    SET NewPath=%DISMRoot%;%ImagingRoot%;%BCDBootRoot%;%OSCDImgRoot%;%WdsmcastRoot%;%HelpIndexerRoot%;%WSIMRoot%;%WinPERoot%;%ICDRoot%

    :SetPath
    SET PATH=%NewPath:"=%;%PATH%
    cd /d "%DandIRoot%"
    set TEMPL=media
    set FWFILES=fwfiles
    set EXITCODE=0
    if /i "%1"=="/?" goto usage
    if /i "%1"=="" goto usage
    if /i "%~2"=="" goto usage
    if /i not "%3"=="" goto usage
    set WINPE_ARCH=%1
    set SOURCE=%WinPERoot%\%WINPE_ARCH%
    set FWFILESROOT=%OSCDImgRoot%\..\..\%WINPE_ARCH%\Oscdimg
    set DEST=%~2
    set WIMSOURCEPATH=%SOURCE%\en-us\winpe.wim
    if not exist "%SOURCE%" (
    echo ERROR: The following processor architecture was not found: %WINPE_ARCH%. >> %~dp0Error.txt
    goto fail
    )

    if not exist "%FWFILESROOT%" (
    echo ERROR: The following path for firmware files was not found: "%FWFILESROOT%". >> %~dp0Error.txt
    goto fail
    )

    if not exist "%WIMSOURCEPATH%" (
    echo ERROR: WinPE WIM file does not exist: "%WIMSOURCEPATH%". >> %~dp0Error.txt
    goto fail
    )

    if exist "%DEST%" (
    echo ERROR: Destination directory exists: "%DEST%">> %~dp0Error.txt
    goto fail
    )

    mkdir "%DEST%"
    if errorlevel 1 (
    echo ERROR: Unable to create destination: "%DEST%". >> %~dp0Error.txt
    goto fail
    )

    echo.
    echo ===================================================
    echo Creating Windows PE customization working directory
    echo.
    echo     %DEST%
    echo ===================================================
    echo.

    mkdir "%DEST%\%TEMPL%"
    if errorlevel 1 (
    echo ERROR: Unable to create directory: "%DEST%\%TEMPL%". >> %~dp0Error.txt
    goto fail
    )

    mkdir "%DEST%\mount"
    if errorlevel 1 (
    echo ERROR: Unable to create directory: "%DEST%\mount". >> %~dp0Error.txt
    goto fail
    )

    mkdir "%DEST%\%FWFILES%"
    if errorlevel 1 (
    echo ERROR: Unable to create directory: "%DEST%\%FWFILES%". >> %~dp0Error.txt
    goto fail
    )

    xcopy /herky "%SOURCE%\Media" "%DEST%\%TEMPL%\"
    if errorlevel 1 (
    echo ERROR: Unable to copy boot files: "%SOURCE%\Media" to "%DEST%\%TEMPL%". >> %~dp0Error.txt
    goto fail
    )

    mkdir "%DEST%\%TEMPL%\sources"
    if errorlevel 1 (
    echo ERROR: Unable to create directory: "%DEST%\%TEMPL%\sources". >> %~dp0Error.txt
    goto fail
    )

    copy "%WIMSOURCEPATH%" "%DEST%\%TEMPL%\sources\boot.wim"
    if errorlevel 1 (
    echo ERROR: Unable to copy WinPE WIM: "%WIMSOURCEPATH%" to "%DEST%\%TEMPL%\sources\boot.wim". >> %~dp0Error.txt
    goto fail
    )

    copy "%FWFILESROOT%\efisys.bin" "%DEST%\%FWFILES%"
    if errorlevel 1 (
    echo ERROR: Unable to copy boot sector file: "%FWFILESROOT%\efisys.bin" to "%DEST%\%FWFILES%". >> %~dp0Error.txt
    goto fail
    )

    if not exist "%FWFILESROOT%\etfsboot.com" goto success

    copy "%FWFILESROOT%\etfsboot.com" "%DEST%\%FWFILES%"
    if errorlevel 1 (
    echo ERROR: Unable to copy boot sector file: "%FWFILESROOT%\etfsboot.com" to "%DEST%\%FWFILES%". >> %~dp0Error.txt
    goto fail 
    )

    :success
    set EXITCODE=0
    echo.
    echo.
    goto cleanup

    :usage
    set EXITCODE=1
    echo Creates working directories for WinPE image customization and media creation.
    echo.
    echo copype { amd64 ^| x86 ^| arm ^| arm64 } ^<workingDirectory^>
    echo.
    echo  amd64             Copies amd64 boot files and WIM to ^<workingDirectory^>\media.
    echo  x86               Copies x86 boot files and WIM to ^<workingDirectory^>\media.
    echo  arm               Copies arm boot files and WIM to ^<workingDirectory^>\media.
    echo  arm64             Copies arm64 boot files and WIM to ^<workingDirectory^>\media.
    echo                    Note: ARM/ARM64 content may not be present in this ADK.
    echo  workingDirectory  Creates the working directory at the specified location.
    echo.
    echo Example: copype amd64 C:\WinPE_amd64
    goto cleanup

    :fail
    set EXITCODE=1
    echo Failed!
    goto cleanup

    :cleanup
    endlocal & exit /b %EXITCODE%
"@
#================================================================
$AddPowerShellbat = @"
    @Echo off

    SET petype=%1
    SET PEDIR=%~2

    if %petype%==x86 goto x86
    if %petype%==amd64 goto amd64

    :x86
    ::Add Powershell
    Dism /Add-Package /Image:"%PEDIR%\Mount" /PackagePath:"C:\Program Files (x86)\Windows Kits\10\Assessment and Deployment Kit\Windows Preinstallation Environment\x86\WinPE_OCs\WinPE-WMI.cab"
    if errorlevel 1 (
    echo ERROR: Could not add WinPE-WMI.cab to WinPE >> %~dp0Error.txt
    goto fail
    )

    Dism /Add-Package /Image:"%PEDIR%\Mount" /PackagePath:"C:\Program Files (x86)\Windows Kits\10\Assessment and Deployment Kit\Windows Preinstallation Environment\x86\WinPE_OCs\en-us\WinPE-WMI_en-us.cab"
    if errorlevel 1 (
    echo ERROR: Could not add WinPE-WMI_en-us to WinPE >> %~dp0Error.txt
    goto fail
    )

    Dism /Add-Package /Image:"%PEDIR%\Mount" /PackagePath:"C:\Program Files (x86)\Windows Kits\10\Assessment and Deployment Kit\Windows Preinstallation Environment\x86\WinPE_OCs\WinPE-NetFX.cab"
    if errorlevel 1 (
    echo ERROR: Could not add WinPE-NetFX.cab to WinPE >> %~dp0Error.txt
    goto fail
    )

    Dism /Add-Package /Image:"%PEDIR%\Mount" /PackagePath:"C:\Program Files (x86)\Windows Kits\10\Assessment and Deployment Kit\Windows Preinstallation Environment\x86\WinPE_OCs\en-us\WinPE-NetFX_en-us.cab"
    if errorlevel 1 (
    echo ERROR: Could not add WinPE-NetFX_en-us.cab to WinPE >> %~dp0Error.txt
    goto fail
    )

    Dism /Add-Package /Image:"%PEDIR%\Mount" /PackagePath:"C:\Program Files (x86)\Windows Kits\10\Assessment and Deployment Kit\Windows Preinstallation Environment\x86\WinPE_OCs\WinPE-Scripting.cab"
    if errorlevel 1 (
    echo ERROR: Could not add WinPE-Scripting.cab to WinPE >> %~dp0Error.txt
    goto fail
    )

    Dism /Add-Package /Image:"%PEDIR%\Mount" /PackagePath:"C:\Program Files (x86)\Windows Kits\10\Assessment and Deployment Kit\Windows Preinstallation Environment\x86\WinPE_OCs\en-us\WinPE-Scripting_en-us.cab"
    if errorlevel 1 (
    echo ERROR: Could not add WinPE-Scripting_en-us.cab to WinPE >> %~dp0Error.txt
    goto fail
    )

    Dism /Add-Package /Image:"%PEDIR%\Mount" /PackagePath:"C:\Program Files (x86)\Windows Kits\10\Assessment and Deployment Kit\Windows Preinstallation Environment\x86\WinPE_OCs\WinPE-PowerShell.cab"
    if errorlevel 1 (
    echo ERROR: Could not add WinPE-PowerShell.cab to WinPE >> %~dp0Error.txt
    goto fail
    )

    Dism /Add-Package /Image:"%PEDIR%\Mount" /PackagePath:"C:\Program Files (x86)\Windows Kits\10\Assessment and Deployment Kit\Windows Preinstallation Environment\x86\WinPE_OCs\en-us\WinPE-PowerShell_en-us.cab"
    if errorlevel 1 (
    echo ERROR: Could not add WinPE-PowerShell_en-us.cab to WinPE >> %~dp0Error.txt
    goto fail
    )

    Dism /Add-Package /Image:"%PEDIR%\Mount" /PackagePath:"C:\Program Files (x86)\Windows Kits\10\Assessment and Deployment Kit\Windows Preinstallation Environment\x86\WinPE_OCs\WinPE-StorageWMI.cab"
    if errorlevel 1 (
    echo ERROR: Could not add inPE-StorageWMI.cab to WinPE >> %~dp0Error.txt
    goto fail
    )

    Dism /Add-Package /Image:"%PEDIR%\Mount" /PackagePath:"C:\Program Files (x86)\Windows Kits\10\Assessment and Deployment Kit\Windows Preinstallation Environment\x86\WinPE_OCs\en-us\WinPE-StorageWMI_en-us.cab"
    if errorlevel 1 (
    echo ERROR: Could not add WinPE-StorageWMI_en-us.cab to WinPE >> %~dp0Error.txt
    goto fail
    )

    Dism /Add-Package /Image:"%PEDIR%\Mount" /PackagePath:"C:\Program Files (x86)\Windows Kits\10\Assessment and Deployment Kit\Windows Preinstallation Environment\x86\WinPE_OCs\WinPE-DismCmdlets.cab"
    if errorlevel 1 (
    echo ERROR: Could not add WinPE-DismCmdlets.cab to WinPE >> %~dp0Error.txt
    goto fail
    )

    Dism /Add-Package /Image:"%PEDIR%\Mount" /PackagePath:"C:\Program Files (x86)\Windows Kits\10\Assessment and Deployment Kit\Windows Preinstallation Environment\x86\WinPE_OCs\en-us\WinPE-DismCmdlets_en-us.cab"
    if errorlevel 1 (
    echo ERROR: Could not add WinPE-DismCmdlets_en-us.cab to WinPE >> %~dp0Error.txt
    goto fail
    )

    goto success


    :amd64
    ::Add Powershell
    Dism /Add-Package /Image:"%PEDIR%\Mount" /PackagePath:"C:\Program Files (x86)\Windows Kits\10\Assessment and Deployment Kit\Windows Preinstallation Environment\amd64\WinPE_OCs\WinPE-WMI.cab"
    if errorlevel 1 (
    echo ERROR: Could not add WinPE-WMI.cab to WinPE >> %~dp0Error.txt
    goto fail
    )

    Dism /Add-Package /Image:"%PEDIR%\Mount" /PackagePath:"C:\Program Files (x86)\Windows Kits\10\Assessment and Deployment Kit\Windows Preinstallation Environment\amd64\WinPE_OCs\en-us\WinPE-WMI_en-us.cab"
    if errorlevel 1 (
    echo ERROR: Could not add WinPE-WMI_en-us.cab to WinPE >> %~dp0Error.txt
    goto fail
    )

    Dism /Add-Package /Image:"%PEDIR%\Mount" /PackagePath:"C:\Program Files (x86)\Windows Kits\10\Assessment and Deployment Kit\Windows Preinstallation Environment\amd64\WinPE_OCs\WinPE-NetFX.cab"
    if errorlevel 1 (
    echo ERROR: Could not add WinPE-NetFX.cab to WinPE >> %~dp0Error.txt
    goto fail
    )

    Dism /Add-Package /Image:"%PEDIR%\Mount" /PackagePath:"C:\Program Files (x86)\Windows Kits\10\Assessment and Deployment Kit\Windows Preinstallation Environment\amd64\WinPE_OCs\en-us\WinPE-NetFX_en-us.cab"
    if errorlevel 1 (
    echo ERROR: Could not add WinPE-NetFX_en-us.cab to WinPE >> %~dp0Error.txt
    goto fail
    )

    Dism /Add-Package /Image:"%PEDIR%\Mount" /PackagePath:"C:\Program Files (x86)\Windows Kits\10\Assessment and Deployment Kit\Windows Preinstallation Environment\amd64\WinPE_OCs\WinPE-Scripting.cab"
    if errorlevel 1 (
    echo ERROR: Could not add WinPE-Scripting.cab to WinPE >> %~dp0Error.txt
    goto fail
    )

    Dism /Add-Package /Image:"%PEDIR%\Mount" /PackagePath:"C:\Program Files (x86)\Windows Kits\10\Assessment and Deployment Kit\Windows Preinstallation Environment\amd64\WinPE_OCs\en-us\WinPE-Scripting_en-us.cab"
    if errorlevel 1 (
    echo ERROR: Could not add WinPE-Scripting_en-us.cab to WinPE >> %~dp0Error.txt
    goto fail
    )

    Dism /Add-Package /Image:"%PEDIR%\Mount" /PackagePath:"C:\Program Files (x86)\Windows Kits\10\Assessment and Deployment Kit\Windows Preinstallation Environment\amd64\WinPE_OCs\WinPE-PowerShell.cab"
    if errorlevel 1 (
    echo ERROR: Could not add WinPE-PowerShell.cab to WinPE >> %~dp0Error.txt
    goto fail
    )

    Dism /Add-Package /Image:"%PEDIR%\Mount" /PackagePath:"C:\Program Files (x86)\Windows Kits\10\Assessment and Deployment Kit\Windows Preinstallation Environment\amd64\WinPE_OCs\en-us\WinPE-PowerShell_en-us.cab"
    if errorlevel 1 (
    echo ERROR: Could not add WinPE-PowerShell_en-us.cab to WinPE >> %~dp0Error.txt
    goto fail
    )

    Dism /Add-Package /Image:"%PEDIR%\Mount" /PackagePath:"C:\Program Files (x86)\Windows Kits\10\Assessment and Deployment Kit\Windows Preinstallation Environment\amd64\WinPE_OCs\WinPE-StorageWMI.cab"
    if errorlevel 1 (
    echo ERROR: Could not add WinPE-StorageWMI.cab to WinPE >> %~dp0Error.txt
    goto fail
    )

    Dism /Add-Package /Image:"%PEDIR%\Mount" /PackagePath:"C:\Program Files (x86)\Windows Kits\10\Assessment and Deployment Kit\Windows Preinstallation Environment\amd64\WinPE_OCs\en-us\WinPE-StorageWMI_en-us.cab"
    if errorlevel 1 (
    echo ERROR: Could not add WinPE-StorageWMI_en-us.cab to WinPE >> %~dp0Error.txt
    goto fail
    )

    Dism /Add-Package /Image:"%PEDIR%\Mount" /PackagePath:"C:\Program Files (x86)\Windows Kits\10\Assessment and Deployment Kit\Windows Preinstallation Environment\amd64\WinPE_OCs\WinPE-DismCmdlets.cab"
    if errorlevel 1 (
    echo ERROR: Could not add WinPE-DismCmdlets.cab to WinPE >> %~dp0Error.txt
    goto fail
    )

    Dism /Add-Package /Image:"%PEDIR%\Mount" /PackagePath:"C:\Program Files (x86)\Windows Kits\10\Assessment and Deployment Kit\Windows Preinstallation Environment\amd64\WinPE_OCs\en-us\WinPE-DismCmdlets_en-us.cab"
    if errorlevel 1 (
    echo ERROR: Could not add WinPE-DismCmdlets_en-us.cab to WinPE >> %~dp0Error.txt
    goto fail
    )

    goto success

    :success
    set EXITCODE=0
    echo.
    echo.
    goto cleanup

    :fail
    set EXITCODE=1
    echo Failed!
    goto cleanup

    :cleanup
    endlocal & exit /b %EXITCODE%
"@
#================================================================
$CopyAppsbat = @"
    @ECHO off

    SET petype=%1
    SET PEDIR=%~2
    SET source=%~3

    if %petype%==x86 goto x86
    if %petype%==amd64 goto amd64

    :x86
    ::Copy application to the program files
    if exist %PEDIR%\Mount\Apps goto copy

    mkdir %PEDIR%\Mount\Apps
    if errorlevel 1 (
        echo ERROR: Could not create %PEDIR%\Mount\Apps >> %~dp0Error.txt
    goto Fail
    )

    :copy
    xcopy %source%Apps_x86 %PEDIR%\Mount\Apps /E
    if errorlevel 1 (
        echo ERROR: Could not copy files to %PEDIR%\Mount\Apps >> %~dp0Error.txt
    goto Fail
    )
    goto success

    :amd64
    ::Copy application to the program files
    if exist %PEDIR%\Mount\Apps goto copy

    mkdir %PEDIR%\Mount\Apps
    if errorlevel 1 (
        echo ERROR: Could not create %PEDIR%\Mount\Apps >> %~dp0Error.txt
    goto Fail
    )

    :copy
    xcopy %source%Apps_x64 %PEDIR%\Mount\Apps /E
    if errorlevel 1 (
        echo ERROR: Could not copy files to %PEDIR%\Mount\Apps >> %~dp0Error.txt
    goto Fail
    )
    goto success

    :success
    set EXITCODE=0
    echo.
    echo.
    goto cleanup

    :fail
    set EXITCODE=1
    echo Failed!
    goto cleanup

    :cleanup
    endlocal & exit /b %EXITCODE%
"@
#================================================================
$CopyBackgroundbat = @"
    @ECHO off

    SET source=%1
    SET PEDIR=%~2

    takeown.exe /F %PEDIR%\Mount\Windows\System32\winpe.jpg
    if errorlevel 1 (
    echo ERROR: Could not take ownership of %PEDIR%\Mount\Windows\System32\winpe.jpg >> %~dp0Error.txt
    goto Fail
    )
    ICACLS %PEDIR%\Mount\Windows\System32\winpe.jpg /Grant %username%:F
    if errorlevel 1 (
    echo ERROR: Could not grant full controll on %PEDIR%\Mount\Windows\System32\winpe.jpg to %USERNAME% >> %~dp0Error.txt
    goto Fail
    )
    xcopy %source% %PEDIR%\Mount\Windows\System32\winpe.jpg /Y
    if errorlevel 1 (
    echo ERROR: Could not copy %source% to %PEDIR%\Mount\Windows\System32\winpe.jpg >> %~dp0Error.txt
    goto Fail
    )

    :success
    set EXITCODE=0
    echo.
    echo.
    goto cleanup

    :fail
    set EXITCODE=1
    echo Failed!
    goto cleanup

    :cleanup
    endlocal & exit /b %EXITCODE%
"@
#================================================================
$CopyStartnetbat = @"
    @ECHO off

    SET source=%1
    SET PEDIR=%~2

    ::Copy Custom startnet.cmd
    takeown.exe /F %PEDIR%\Mount\Windows\System32\Startnet.cmd
    if errorlevel 1 (
    echo ERROR: Could not take ownership of %PEDIR%\Mount\Windows\System32\Startnet.cmd >> %~dp0Error.txt
    goto Fail
    )
    ICACLS %PEDIR%\Mount\Windows\System32\Startnet.cmd /Grant %username%:F
    if errorlevel 1 (
    echo ERROR: Could not grant full controll on %PEDIR%\Mount\Windows\System32\Startnet.cmd to %USERNAME% >> %~dp0Error.txt
    goto Fail
    )
    xcopy %source% %PEDIR%\Mount\Windows\System32\Startnet.cmd /Y
    if errorlevel 1 (
    echo ERROR: Could not copy %source% to %PEDIR%\Mount\Windows\System32\Startnet.cmd >> %~dp0Error.txt
    goto Fail
    )

    :success
    set EXITCODE=0
    echo.
    echo.
    goto cleanup

    :fail
    set EXITCODE=1
    echo Failed!
    goto cleanup

    :cleanup
    endlocal & exit /b %EXITCODE%

"@
#================================================================
$CopyWinpeshlbat = @"
    @ECHO off

    SET source=%1
    SET PEDIR=%~2

    REM ::Copy Custom startnet.cmd
    REM takeown.exe /F %PEDIR%\Mount\Windows\System32\Startnet.cmd
    REM if errorlevel 1 (
    REM   echo ERROR: Could not take ownership of %PEDIR%\Mount\Windows\System32\Startnet.cmd >> %~dp0Error.txt
    REM   goto Fail
    REM )
    REM ICACLS %PEDIR%\Mount\Windows\System32\Startnet.cmd /Grant %username%:F
    REM if errorlevel 1 (
    REM   echo ERROR: Could not grant full controll on %PEDIR%\Mount\Windows\System32\Startnet.cmd to %USERNAME% >> %~dp0Error.txt
    REM   goto Fail
    REM )
    xcopy %source% %PEDIR%\Mount\Windows\system32 /Y
    if errorlevel 1 (
    echo ERROR: Could not copy %source% to %PEDIR%\Mount\Windows\winpeshl.ini >> %~dp0Error.txt
    goto Fail
    )

    :success
    set EXITCODE=0
    echo.
    echo.
    goto cleanup

    :fail
    set EXITCODE=1
    echo Failed!
    goto cleanup

    :cleanup
    endlocal & exit /b %EXITCODE%

"@
#================================================================
$MakePEMediabat = @"
    @Echo off

    REM Sets the PROCESSOR_ARCHITECTURE according to native platform for x86 and x64. 
    IF /I %PROCESSOR_ARCHITECTURE%==x86 (
        IF NOT "%PROCESSOR_ARCHITEW6432%"=="" (
            SET PROCESSOR_ARCHITECTURE=%PROCESSOR_ARCHITEW6432%
        )
    ) ELSE IF /I NOT %PROCESSOR_ARCHITECTURE%==amd64 (
        @echo Not implemented for PROCESSOR_ARCHITECTURE of %PROCESSOR_ARCHITECTURE%.
        @echo Using "%ProgramFiles%"
        
        SET NewPath="%ProgramFiles%"

        goto SetPath
    )

    REM Query the 32-bit and 64-bit Registry hive for KitsRoot

    SET regKeyPathFound=1
    SET wowRegKeyPathFound=1
    SET KitsRootRegValueName=KitsRoot10

    REG QUERY "HKLM\Software\Wow6432Node\Microsoft\Windows Kits\Installed Roots" /v %KitsRootRegValueName% 1>NUL 2>NUL || SET wowRegKeyPathFound=0
    REG QUERY "HKLM\Software\Microsoft\Windows Kits\Installed Roots" /v %KitsRootRegValueName% 1>NUL 2>NUL || SET regKeyPathFound=0

    if %wowRegKeyPathFound% EQU 0 (
    if %regKeyPathFound% EQU 0 (
        @echo KitsRoot not found, can't set common path for Deployment Tools
        goto :EOF 
    ) else (
        SET regKeyPath=HKLM\Software\Microsoft\Windows Kits\Installed Roots
    )
    ) else (
        SET regKeyPath=HKLM\Software\Wow6432Node\Microsoft\Windows Kits\Installed Roots
    )

    FOR /F "skip=2 tokens=2*" %%i IN ('REG QUERY "%regKeyPath%" /v %KitsRootRegValueName%') DO (SET KitsRoot=%%j)

    REM Build the D&I Root from the queried KitsRoot
    SET DandIRoot=%KitsRoot%Assessment and Deployment Kit\Deployment Tools

    REM Construct the path to WinPE directory, architecture-independent
    SET WinPERoot=%KitsRoot%Assessment and Deployment Kit\Windows Preinstallation Environment
    SET WinPERootNoArch=%KitsRoot%Assessment and Deployment Kit\Windows Preinstallation Environment

    REM Construct the path to DISM, Setup and USMT, architecture-independent
    SET WindowsSetupRootNoArch=%KitsRoot%Assessment and Deployment Kit\Windows Setup
    SET USMTRootNoArch=%KitsRoot%Assessment and Deployment Kit\User State Migration Tool

    REM Constructing tools paths relevant to the current Processor Architecture 
    SET DISMRoot=%DandIRoot%\%PROCESSOR_ARCHITECTURE%\DISM
    SET BCDBootRoot=%DandIRoot%\%PROCESSOR_ARCHITECTURE%\BCDBoot
    SET ImagingRoot=%DandIRoot%\%PROCESSOR_ARCHITECTURE%\Imaging
    SET OSCDImgRoot=%DandIRoot%\%PROCESSOR_ARCHITECTURE%\Oscdimg
    SET WdsmcastRoot=%DandIRoot%\%PROCESSOR_ARCHITECTURE%\Wdsmcast

    REM Now do the paths that apply to all architectures...
    REM Note that the last one in this list should not have a
    REM trailing semi-colon to avoid duplicate semi-colons
    REM on the last entry when the final path is assembled.
    SET HelpIndexerRoot=%DandIRoot%\HelpIndexer
    SET WSIMRoot=%DandIRoot%\WSIM

    REM Set ICDRoot. ICD is X86 only
    SET ICDRoot=%KitsRoot%Assessment and Deployment Kit\Imaging and Configuration Designer\x86

    REM Now buld the master path from the various tool root folders...
    REM Note that each fragment above should have any required trailing 
    REM semi-colon as a delimiter so we do not put any here.
    REM Note the last one appended to NewPath should be the last one
    REM set above in the arch. neutral section which also should not
    REM have a trailing semi-colon.
    SET NewPath=%DISMRoot%;%ImagingRoot%;%BCDBootRoot%;%OSCDImgRoot%;%WdsmcastRoot%;%HelpIndexerRoot%;%WSIMRoot%;%WinPERoot%;%ICDRoot%

    :SetPath
    SET PATH=%NewPath:"=%;%PATH%

    REM Set current directory to DandIRoot
    cd /d "%DandIRoot%"

    setlocal

    rem
    rem Set variables for local use
    rem
    set TEMPL=media
    set FWFILES=fwfiles
    set DISKPARTSCRIPT=%TMP%\UFDFormatDiskpartScript.txt
    set EXITCODE=0

    rem
    rem Input validation
    rem
    if /i "%1"=="/?" goto usage
    if /i "%1"=="" goto usage
    if /i "%~2"=="" goto usage
    if /i "%~3"=="" goto usage
    if /i not "%~5"=="" goto usage
    if /i not "%1"=="/UFD" (
    if /i not "%1"=="/ISO" goto usage
    )

    rem
    rem Based on parameters input, assign local variables
    rem
    if /i "%~2"=="/f" (
    set FORCED=1
    set WORKINGDIR=%~3
    set DEST=%~4
    ) else (
    set FORCED=0
    set WORKINGDIR=%~2
    set DEST=%~3
    )

    rem
    rem Make sure the working directory exists
    rem
    if not exist "%WORKINGDIR%" (
    echo ERROR: Working directory does not exist: "%WORKINGDIR%". >> %~dp0Error.txt
    goto fail
    )

    rem
    rem Make sure the working directory is valid as per our requirements
    rem
    if not exist "%WORKINGDIR%\%TEMPL%" (
    echo ERROR: Working directory is not valid: "%WORKINGDIR%". >> %~dp0Error.txt
    goto fail
    )

    if not defined %TMP% (
    set DISKPARTSCRIPT=.\UFDFormatDiskpartScript.txt
    )

    if /i "%1"=="/UFD" goto UFDWorker

    if /i "%1"=="/ISO" goto ISOWorker

    rem
    rem UFD section of the script, for creating bootable WinPE UFD
    rem
    :UFDWorker

    rem
    rem Make sure the user has administrator privileges
    rem These will be required to format the drive and set the boot code
    rem
    set ADMINTESTDIR=%WINDIR%\System32\Test_%RANDOM%
    mkdir "%ADMINTESTDIR%" 2>NUL
    if errorlevel 1 (
        echo ERROR: You need to run this command with administrator privileges. >> %~dp0Error.txt
        goto fail
    ) else (
        rd /s /q "%ADMINTESTDIR%"
    )

    rem
    rem Make sure the destination refers to a storage drive,
    rem and is not any other type of path
    rem
    echo %DEST%| findstr /B /E /I "[A-Z]:" >NUL
    if errorlevel 1 (
        echo ERROR: Destination needs to be a disk drive, e.g F:. >> %~dp0Error.txt
        goto fail
    )

    rem
    rem Make sure the destination path exists
    rem
    if not exist "%DEST%" (
        echo ERROR: Destination drive "%DEST%" does not exist. >> %~dp0Error.txt
        goto fail
    )

    if %FORCED% EQU 1 goto UFDWorker_FormatUFD

    rem
    rem Confirm from the user that they want to format the drive
    rem
    echo WARNING, ALL DATA ON DISK DRIVE %DEST% WILL BE LOST!
    choice /M "Proceed with Format "
    if errorlevel 2 goto UFDWorker_NoFormatUFD
    if errorlevel 1 goto UFDWorker_FormatUFD

    :UFDWorker_NoFormatUFD
    echo UFD %DEST% will not be formatted; exiting.
    goto cleanup

    :UFDWorker_FormatUFD
    rem
    rem Format the volume using diskpart, in FAT32 file system
    rem
    echo select volume=%DEST% > "%DISKPARTSCRIPT%"
    echo format fs=fat32 label="WinPE" quick >> "%DISKPARTSCRIPT%"
    echo active >> "%DISKPARTSCRIPT%"
    echo Formatting %DEST%...
    echo.
    diskpart /s "%DISKPARTSCRIPT%" >NUL
    set DISKPARTERR=%ERRORLEVEL%

    del /F /Q "%DISKPARTSCRIPT%"
    if errorlevel 1 (
        echo WARNING: Failed to delete temporary DiskPart script "%DISKPARTSCRIPT%".
    )
    
    if %DISKPARTERR% NEQ 0 (
        echo ERROR: Failed to format "%DEST%"; DiskPart errorlevel %DISKPARTERR%. >> %~dp0Error.txt
        goto fail
    )

    rem
    rem Set the boot code on the volume using bootsect.exe
    rem
    echo Setting the boot code on %DEST%...
    echo.
    bootsect.exe /nt60 %DEST% /force /mbr >NUL
    if errorlevel 1 (
        echo ERROR: Failed to set the boot code on %DEST%. >> %~dp0Error.txt
        goto fail
    )

    rem
    rem We first decompress the source directory that we are copying from.
    rem  This is done to work around an issue with xcopy when working with
    rem  compressed NTFS source directory.
    rem
    rem Note that this command will not cause an error on file systems that
    rem  do not support compression - because we do not use /f.
    rem
    compact /u "%WORKINGDIR%\%TEMPL%" >NUL
    if errorlevel 1 (
        echo ERROR: Failed to decompress "%WORKINGDIR%\%TEMPL%". >> %~dp0Error.txt
        goto fail
    )

    rem
    rem Copy the media files from the user-specified working directory
    rem
    echo Copying files to %DEST%...
    echo.
    xcopy /herky "%WORKINGDIR%\%TEMPL%\*.*" "%DEST%\" >NUL
    if errorlevel 1 (
        echo ERROR: Failed to copy files to "%DEST%\". >> %~dp0Error.txt
        goto fail
    )

    goto success

    rem
    rem ISO section of the script, for creating bootable ISO image
    rem
    :ISOWorker

    rem
    rem Make sure the destination refers to an ISO file, ending in .ISO
    rem
    echo %DEST%| findstr /E /I "\.iso" >NUL
    if errorlevel 1 (
        echo ERROR: Destination needs to be an .ISO file. >> %~dp0Error.txt
        goto fail
    )

    if not exist "%DEST%" goto ISOWorker_OscdImgCommand

    if %FORCED% EQU 1 goto ISOWorker_CleanDestinationFile

    rem
    rem Confirm from the user that they want to overwrite the existing ISO file
    rem
    choice /M "Destination file %DEST% exists, overwrite it "
    if errorlevel 2 goto ISOWorker_DestinationFileExists
    if errorlevel 1 goto ISOWorker_CleanDestinationFile

    :ISOWorker_DestinationFileExists
    echo Destination file %DEST% will not be overwritten; exiting.
    goto cleanup

    :ISOWorker_CleanDestinationFile
    rem
    rem Delete the existing ISO file
    rem
    del /F /Q "%DEST%"
    if errorlevel 1 (
        echo ERROR: Failed to delete "%DEST%". >> %~dp0Error.txt
        goto fail
    )

    :ISOWorker_OscdImgCommand

    rem
    rem Set the correct boot argument based on availability of boot apps
    rem
    set BOOTDATA=1#pEF,e,b"%WORKINGDIR%\%FWFILES%\efisys.bin"
    if exist "%WORKINGDIR%\%FWFILES%\etfsboot.com" (
        set BOOTDATA=2#p0,e,b"%WORKINGDIR%\%FWFILES%\etfsboot.com"#pEF,e,b"%WORKINGDIR%\%FWFILES%\efisys.bin"
    )

    rem
    rem Create the ISO file using the appropriate OSCDImg command
    rem
    echo Creating %DEST%...
    echo.
    oscdimg -bootdata:%BOOTDATA% -u1 -udfver102 "%WORKINGDIR%\%TEMPL%" "%DEST%" >NUL
    if errorlevel 1 (
        echo ERROR: Failed to create "%DEST%" file. >> %~dp0Error.txt
        goto fail
    )

    goto success

    :success
    set EXITCODE=0
    echo.
    echo.
    goto cleanup

    :usage
    set EXITCODE=1
    echo Creates bootable WinPE USB flash drive or ISO file.
    echo.
    echo MakeWinPEMedia {/ufd ^| /iso} [/f] ^<workingDirectory^> ^<destination^>
    echo.
    echo  /ufd              Specifies a USB Flash Drive as the media type.
    echo                    NOTE: THE USB FLASH DRIVE WILL BE FORMATTED.
    echo  /iso              Specifies an ISO file (for CD or DVD) as the media type.
    echo  /f                Suppresses prompting to confirm formatting the UFD
    echo                    or overwriting existing ISO file.
    echo  workingDirectory  Specifies the working directory created using copype.cmd
    echo                    The contents of the ^<workingDirectory^>\media folder
    echo                    will be copied to the UFD or ISO.
    echo  destination       Specifies the UFD volume or .ISO path and file name.
    echo.
    echo  Examples:
    echo    MakeWinPEMedia /UFD C:\WinPE_amd64 G:
    echo    MakeWinPEMedia /UFD /F C:\WinPE_amd64 H:
    echo    MakeWinPEMedia /ISO C:\WinPE_x86 C:\WinPE_x86\WinPE_x86.iso
    goto cleanup

    :fail
    set EXITCODE=1
    goto cleanup

    :cleanup
    endlocal & exit /b %EXITCODE%
"@
#================================================================
#END OF DO NOT CHANGE

Write-Host "============================================"
Write-Host $StartMessage

Function Get-Error
{
    $ErrorText = Get-Content -Path $ENV:Temp\Error.txt
    Write-Error "$ErrorText"
    Remove-Item $ENV:Temp\Error.txt
    exit
}

IF (($InstallADK) -or (!(Test-Path 'C:\Program Files (x86)\Windows Kits\10\Assessment and Deployment Kit')))
{
    mkdir $PSScriptRoot\Temp | Out-Null
    $WebClient = New-Object System.Net.WebClient
    Write-Host "Downloading ADK 1703" -ForegroundColor "$StatusColor"
    $WebClient.DownloadFile("https://go.microsoft.com/fwlink/p/?LinkId=845542","$PSScriptRoot\Temp\adksetup1703.exe")
    start-sleep 10
    Set-location $PSScriptRoot\Temp
    Invoke-Expression ".\adksetup1703.exe /quiet /features OptionId.DeploymentTools OptionId.WindowsPreinstallationEnvironment OptionId.ICDConfigurationDesigner"
    Write-Host "Installing ADK 1703..." -ForegroundColor "$StatusColor"
    Write-Host "Please wait this may take sometime" -ForegroundColor "$StatusColor"
    wait-Process -Name adksetup1703
    Set-location $PSScriptRoot
    Start-Sleep 10
    Remove-Item $PSScriptRoot\Temp -Recurse -Force
}

IF ($CopyPE)
{
    Write-Host "Copying PE to $PEBuildLocation" -ForegroundColor "$StatusColor"
    IF ((!($PEType)) -or (!($PEBuildLocation)))
    {
        Write-Error "ERROR: You must set PEType and PEBuildLocation to use CopyPE"
        exit
    }
    add-content $Env:TEMP\CopyPE.bat $CopyPEBat
    Invoke-Expression "$Env:TEMP\CopyPE.bat $PEType $PEBuildLocation"
    Remove-Item "$env:temp\copype.bat" -Force
    IF ($LASTEXITCODE -eq 1) {Get-Error}
    IF ($LASTEXITCODE -eq 0) {Write-Host "SUCCESS: Created files for WinPE $PEType at $PEBuildLocation" -ForegroundColor "$SuccessColor"}
    Write-Host ""
    IF (!(Test-Path $PEBuildLocation\Mount))
    {
        Write-Error "ERROR: Cannot fine $PEBuildLocation"
        exit
    }
    IF (!(Test-Path $PEBuildLocation\media\sources\boot.wim))
    {
        Write-Error "ERROR: Cannot find $PEBuildLocation\media\sources\boot.wim"
        exit
    }
    Dism /Mount-Image /ImageFile:"$PEBuildLocation\media\sources\boot.wim" /index:1 /MountDir:"$PEBuildLocation\Mount"
    Write-Host ""
}

IF ($MountPE)
{
    Write-Host "Mounting WinPE" -ForegroundColor "$StatusColor"
    IF (!($PEBuildLocation))
    {
        Write-Error "ERROR: You must set PEBuildLocation to use MountPE"
        exit
    }
    IF (!(Test-Path $PEBuildLocation\Mount))
    {
        Write-Error "ERROR: Cannot fine $PEBuildLocation"
        exit
    }
    IF (!(Test-Path $PEBuildLocation\media\sources\boot.wim))
    {
        Write-Error "ERROR: Cannot find $PEBuildLocation\media\sources\boot.wim"
        exit
    }
    Dism /Mount-Image /ImageFile:"$PEBuildLocation\media\sources\boot.wim" /index:1 /MountDir:"$PEBuildLocation\Mount"
}

IF ($AddPowerShell)
{
    Write-Host "Adding PowerShell" -ForegroundColor "$StatusColor"
    IF ((!($PEType)) -or (!($PEBuildLocation)))
    {
        Write-Error "ERROR: You must set PEType and PEBuildLocation to use this AddPowerShell"
        exit
    }
    IF (!(Test-path $PEBuildLocation)) 
    {
        Write-Error "ERROR: can not locate $PEBuildLocation to run AddPowerShell"
        exit
    }
    Add-Content $Env:TEMP\AddPowerShell.bat $AddPowerShellbat
    Invoke-Expression "$env:temp\AddPowershell.bat $PEType $PEBuildLocation"
    Remove-Item "$env:temp\AddPowershell.bat"
    IF ($LASTEXITCODE -eq 1) {Get-Error}
    IF ($LASTEXITCODE -eq 0) {Write-Host "SUCCESS: Added PowerShell to WinPE" -ForegroundColor "$SuccessColor"}
    Write-Host ""
}

if ($CustomWinpeshl)
{
    Write-Host "Copying custome Winpeshl.ini file" -ForegroundColor "$StatusColor"
    IF (!($PEBuildLocation)) 
    {
        Write-Error "ERROR: You must set PEBuildLocation to use CustomStartnet"
        exit
    }
    IF (!(Test-path $PEBuildLocation)) 
    {
        Write-Error "ERROR: can not locate $PEBuildLocation to run CustomStartnet"
        exit
    }
    Add-Content $Env:TEMP\CopyWinpeshl.bat $CopyWinpeshlbat
    Invoke-Expression "$Env:TEMP\CopyWinpeshl.bat $PSScriptroot\PE_SourceFiles\winpeshl\winpeshl.ini $PEBuildLocation"
    Remove-Item $Env:TEMP\CopyWinpeshl.bat
    IF ($LASTEXITCODE -eq 1) {Get-Error}
    IF ($LASTEXITCODE -eq 0) {Write-Host "SUCCESS: Added custom startnet file" -ForegroundColor "$SuccessColor"}
    Write-Host ""
    
}

if ($CustomStartnet)
{
    Write-Host "Copying custom startnet.cmd file" -ForegroundColor "$StatusColor"
    IF (!($PEBuildLocation)) 
    {
        Write-Error "ERROR: You must set PEBuildLocation to use CustomStartnet"
        exit
    }
    IF (!(Test-path $PEBuildLocation)) 
    {
        Write-Error "ERROR: can not locate $PEBuildLocation to run CustomStartnet"
        exit
    }
    Add-Content $Env:TEMP\CopyStartnet.bat $CopyStartnetbat
    Invoke-Expression "$Env:TEMP\CopyStartnet.bat $PSScriptroot\PE_SourceFiles\startnet\startnet.cmd $PEBuildLocation"
    Remove-Item $Env:TEMP\CopyStartnet.bat
    IF ($LASTEXITCODE -eq 1) {Get-Error}
    IF ($LASTEXITCODE -eq 0) {Write-Host "SUCCESS: Added custom startnet file" -ForegroundColor "$SuccessColor"}
    Write-Host ""
    
}

if ($Custombackground)
{
    Write-Host "Copying custom background image" -ForegroundColor "$StatusColor"
    IF (!($PEBuildLocation)) 
    {
        Write-Error "ERROR: You must set PEBuildLocation to use CustomBackground"
        exit
    }
    IF (!(Test-path $PEBuildLocation)) 
    {
        Write-Error "ERROR: can not locate $PEBuildLocation to run CopyBackground"
        exit
    }
    Add-Content $Env:TEMP\CopyBackground.bat $CopyBackgroundbat
    Invoke-Expression "$Env:TEMP\CopyBackground.bat $PSScriptroot\PE_SourceFiles\Background\winpe.jpg $PEBuildLocation "
    Remove-Item $Env:TEMP\CopyBackground.bat
    IF ($LASTEXITCODE -eq 1) {Get-Error}
    IF ($LASTEXITCODE -eq 0) {Write-Host "SUCCESS: Added custom background file" -ForegroundColor "$SuccessColor"}
    Write-Host ""
}

if ($AddPSProfile)
{   
    Write-Host "Copying custom powershell profile" -ForegroundColor "$StatusColor"
    IF (!(Test-path $PEBuildLocation)) 
    {
        Write-Error "ERROR: can not locate $PEBuildLocation to run CopyApps"
        exit
    }
    IF (!($AddPowerShell)) {Write-Warning "The AddPowerShell paramater was not used. PowerShell will not be addded to the image by PEBuilder"}
    Copy-Item $PSScriptRoot\PE_SourceFiles\PSProfile\Profile.ps1 $PEBuildLocation\Mount\Windows\System32\WindowsPowerShell\v1.0
    If (Test-Path $PEBuildLocation\Mount\Windows\System32\WindowsPowerShell\v1.0\Profile.ps1) {Write-Host "SUCCESS: Added PowerShell Profile" -ForegroundColor "$SuccessColor"}
    If (!(Test-Path $PEBuildLocation\Mount\Windows\System32\WindowsPowerShell\v1.0\Profile.ps1)) 
    {
        Write-Error "ERROR: Could not add PowerShell Profile" -ForegroundColor "$Errorcolor"
        Exit
    }
    Write-Host""
}

if ($CopyApps)
{
    Write-Host "Copying custom apps" -ForegroundColor "$StatusColor"
    IF ((!($PEType)) -or (!($PEBuildLocation)))
    {
        Write-Error "ERROR: You must set PEType and PEBuildLocation to use CopyApps"
        exit
    }
    IF (!(Test-path $PEBuildLocation)) 
    {
        Write-Error "ERROR: can not locate $PEBuildLocation to run CopyApps"
        exit
    }
    Add-Content $Env:TEMP\CopyApps.bat $CopyAppsbat
    Invoke-Expression "$Env:TEMP\CopyApps.bat $PEType $PEBuildLocation $PSScriptroot\PE_SourceFiles\"
    Remove-Item $Env:TEMP\CopyApps.bat
    IF ($LASTEXITCODE -eq 1) {Get-Error}
    IF ($LASTEXITCODE -eq 0) {Write-Host "SUCCESS: Added all $PEType apps" -ForegroundColor "$SuccessColor"}
    Write-Host ""
}

If ($AddAutoRun)
{
    Write-Host "Adding Autorun files" -ForegroundColor "$StatusColor"
    If (!($PEBuildLocation))
    {
        Write-Error "ERROR: You must specify the PEBuildLocation to run AddAutoRun"
        Exit
    }
    IF (!(Test-path $PEBuildLocation)) 
    {
        Write-Error "ERROR: can not locate $PEBuildLocation to run CopyApps"
        exit
    }
    $AutorunFiles = Get-ChildItem $PSScriptRoot\PE_SourceFiles\Autorun
    foreach ($File in $AutorunFiles)
    {
        Copy-Item $PSScriptRoot\PE_SourceFiles\Autorun\$File $PEBuildLocation\media
        IF (!(Test-Path $PEBuildLocation\media\$File))
        {
            Write-error "ERROR: $File was not compied to $PEBuildLocation\media" -ForegroundColor "$ErrorColor"
            exit
        }
    }
    Write-Host "SUCCESS: Added Autorun files" -ForegroundColor "$SuccessColor"
    Write-Host ""
}

IF ($DismountPE)
{
    Write-Host "Dismounting WinPE" -ForegroundColor "$StatusColor"
    IF (!($PEBuildLocation))
    {
        Write-Error "ERROR: You must set PEBuildLocation to use DismountPE"
        exit
    }
    $Stat = Read-Host "Commit or Discard changes to mounted image"
    Dism /Unmount-Image /MountDir:$PEBuildLocation\Mount /$Stat
}

IF ($CreateISO)
{
    Write-Host "Creating ISO" -ForegroundColor "$StatusColor"
    IF (!($PEBuildLocation)) 
    {
        Write-Error "ERROR: You must set PEBuildLocation to use this parameter"
        exit
    }
    IF (!(Test-path $PEBuildLocation)) 
    {
        Write-Error "ERROR: can not locate $PEBuildLocation"
        exit
    }
    Dism /Unmount-Image /MountDir:$PEBuildLocation\Mount /commit | Out-Null
    Add-Content $Env:TEMP\MakePEMedia.bat $MakePEMediabat
    Invoke-Expression "$Env:TEMP\MakePEMedia.bat /ISO $PEBuildlocation $CreateISO"
    Remove-Item $Env:TEMP\MakePEMedia.bat
    IF ($LASTEXITCODE -eq 1) {Get-Error}
    IF ($LASTEXITCODE -eq 0) {Write-Host "SUCCESS: Created $CreateISO" -ForegroundColor "$SuccessColor"}
    Write-Host ""
}

IF ($BurnToUSB)
{
    Write-Host "Burning WInPE to $BurnToUSB" -ForegroundColor "$StatusColor"
    IF (!($PEBuildLocation)) 
    {
        Write-Error "ERROR: You must set PEBuildLocation to use this parameter"
        exit
    }
    IF (!(Test-path $PEBuildLocation)) 
    {
        Write-Error "ERROR: can not locate $PEBuildLocation"
        exit
    }
    Dism /Unmount-Image /MountDir:$PEBuildLocation\Mount /commit | Out-Null
    Add-Content $Env:TEMP\MakePEMedia.bat $MakePEMediabat
    Invoke-Expression "$Env:TEMP\MakePEMedia.bat /UFD $PEBuildlocation $BurnToUSB"
    Remove-Item $Env:TEMP\MakePEMedia.bat
    IF ($LASTEXITCODE -eq 1) {Get-Error}
    IF ($LASTEXITCODE -eq 0) {Write-Host "SUCCESS: Bunred WinPE to $BurnToUSB" -ForegroundColor "$SuccessColor"}
    Write-Host ""
    
}

If ($DeletePE)
{
    Write-Host "Deleteing $PEBuildLocation" -ForegroundColor "$StatusColor"
    Dism /Unmount-Image /MountDir:$PEBuildLocation\Mount /discard | Out-Null
    Remove-Item $PEBuildLocation -Recurse -Force
    IF (Test-Path $PEBuildLocation)
    {
        Write-Error "ERROR:$PEbuildLocation was not deleted"
        exit
    }
}


Write-Host ""
Write-Host "SUCCESS: All Actions Completed" -ForegroundColor "$SuccessColor"

Comments

Popular posts from this blog

SCCM Task Sequence GUI - How to set up the TS to work with a GUI

SCCM Applications vs. SCCM Packages: Understanding the Key Differences

How to Deploy a Windows 10 Servicing update as a Application