LoginSignup
1
1

バッチファイルで WinPE ISO ファイルから Bootable USB Memory を作る

Last updated at Posted at 2024-01-15

文字コードは ANSI 形式で保存してください。

CreateBootableUSBMemory.bat
@echo off
for /f "usebackq tokens=2 delims=:" %%A in (`chcp`) do (set "ACTIVE_CP=%%A")
chcp 932 >nul
setlocal

set /a Arg_R=0
set /a Arg_S=0
for %%a in (%*) do (
	if /i %%a==/R (set /a Arg_R=1)
	if /i %%a==/S (set /a Arg_S=1)
)

:checkMandatoryLevel
	set "BatchArgs=%*"
	call :checkMandatoryLevelandElevate
	if %errorlevel% equ 0 (
		set "gtLBL=admins"
	) else (
		set "gtLBL=exit1"
	)
	goto %gtLBL%

:admins
	set "BatchDir=%~dp0"
	set PSCommand=^
		Add-Type -AssemblyName System.Windows.Forms;^
		$TargetUD = Get-Disk ^|^
			Where-Object {$_.BusType -eq 'USB'} ^|^
			Out-GridView -Title 'フォーマットする USB メモリを選択してください' -OutputMode Single;^
		if ($null -ne $TargetUD) {^
			Write-Host "USB メモリ: $($TargetUD | Out-String)" -NoNewLine;^
			$FileDialog = New-Object System.Windows.Forms.OpenFileDialog;^
			$FileDialog.Filter = 'ISO Files^|*.iso^|All Files^|*.*';^
			$FileDialog.InitialDirectory = $env:BatchDir;^
			$FileDialog.Title = 'ISO ファイルを選択してください';^
			if ($FileDialog.ShowDialog() -eq [System.Windows.Forms.DialogResult]::OK) {^
				$Iso_Path = $FileDialog.FileName;^
				Write-Host "ISO ファイル: `n$Iso_Path`n";^
				$UserInput = Read-Host 'WinPE ISO ファイルからブータブル USB メモリの作成処理を開始します。よろしいですか(YES/NO)';^
				if ($UserInput -eq 'YES') {^
					Write-Host 'USB メモリの初期化..';^
					if ($TargetUD.PartitionStyle -ne 'RAW') {^
						Clear-Disk -Number $TargetUD.Number -RemoveData -RemoveOEM -Confirm:$false;^
					}^
					Set-Disk -Number $TargetUD.Number -PartitionStyle MBR 2^> $null;^
					if (!$?) {^
						Initialize-Disk -Number $TargetUD.Number -PartitionStyle MBR;^
					}^
					$TargetUD_P = New-Partition -DiskNumber $TargetUD.Number -UseMaximumSize -IsActive;^
					if ($TargetUD_P.Size -gt 34359738368) {^
						Resize-Partition -InputObject $TargetUD_P -Size 34359738368;^
					}^
					Format-Volume -Partition $TargetUD_P -FileSystem FAT32 ^| Get-Partition ^| Add-PartitionAccessPath -AssignDriveLetter;^
					$TargetUD_DL = (Get-Partition -DiskNumber $TargetUD.Number -PartitionNumber $TargetUD_P.PartitionNumber).DriveLetter;^
					$TargetUD_D = $TargetUD_DL + ':';^
					$Iso_Mount_Owner = $false;^
					if ((Get-DiskImage -ImagePath $Iso_Path).Attached) {^
						$Iso_DL = (Get-DiskImage -ImagePath $Iso_Path ^| Get-Volume).DriveLetter;^
					} else {^
						$Iso_Mount_Owner = $true;^
						$Iso_DL = (Mount-DiskImage -ImagePath $Iso_Path ^| Get-Volume).DriveLetter;^
					}^
					$Iso_D = $Iso_DL + ':';^
					$TargetUD_FSVL = (Get-Volume -DriveLetter $Iso_DL).FileSystemLabel;^
					if ([System.Text.Encoding]::Default.GetByteCount($TargetUD_FSVL) -gt 11) {^
						$str_byteCount = 0;^
						$n = 0;^
						while (($n -lt 11) -and ($str_byteCount -lt 11)) {^
							$str_byteCount += [System.Text.Encoding]::Default.GetByteCount($TargetUD_FSVL[$n]);^
							$n++;^
						}^
						if ($str_byteCount -gt 11) {^
							$n--;^
						}^
						$TargetUD_FSVL = $TargetUD_FSVL.SubString(0, $n);^
					}^
					if ('' -ne $TargetUD_FSVL) {^
						Get-Volume -DriveLetter $TargetUD_DL ^| Set-Volume -NewFileSystemLabel $TargetUD_FSVL;^
					}^
					^
					Write-Host 'ファイルのコピー..';^
					robocopy $Iso_D $TargetUD_D /s /e /max:4294967295 ^>$null;^
					$Iso_D_installwim = $Iso_D + '\sources\install.wim';^
					if (Test-Path -LiteralPath $Iso_D_installwim -PathType Leaf) {^
						if ((Get-Item -Path $Iso_D_installwim).Length -ge 4294967296) {^
							$TargetUD_D_installswm = $TargetUD_D + '\sources\install.swm';^
							dism /Split-Image /ImageFile:$Iso_D_installwim /SWMFile:$TargetUD_D_installswm /FileSize:4095;^
						}^
					}^
					$Iso_D_installesd = $Iso_D + '\sources\install.esd';^
					if (Test-Path -LiteralPath $Iso_D_installesd -PathType Leaf) {^
						if ((Get-Item -Path $Iso_D_installesd).Length -ge 4294967296) {^
							$TargetUD_D_installswm = $TargetUD_D + '\sources\install.swm';^
							dism /Split-Image /ImageFile:$Iso_D_installesd /SWMFile:$TargetUD_D_installswm /FileSize:4095;^
						}^
					}^
					^
					$bootsectexe = $Iso_D + '\boot\bootsect.exe';^
					if (!(Test-Path -LiteralPath $bootsectexe -PathType Leaf)) {^
						$bootsectexe = 'bootsect.exe';^
					}^
					$bootsectcmd = $bootsectexe + ' /nt60 ' + $TargetUD_D + ' /force';^
					Write-Host '起動環境の構成..';^
					Invoke-Expression -Command $bootsectcmd;^
					^
					if ($Iso_Mount_Owner) {^
						DisMount-DiskImage -ImagePath $Iso_Path ^>$null;^
					}^
				}^
			}^
		}
	
	echo WinPE ISO ファイルからブータブル USB メモリを作成...
	powershell -NoProfile -Command "Invoke-Expression -Command $env:PSCommand;"
	
	if %Arg_S% equ 0 pause
	
	goto exit1

:checkMandatoryLevelandElevate
	set "FP=%~f0"
	set PSCommand=^
		if (!([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) {^
			Write-Host 'このファイルは管理者権限での実行が必要です [プロセスの昇格が必要]';^
			$returnValue = 2;^
			if ($env:Arg_R -eq 1) {^
				$returnValue = 3;^
			} else {^
				$FP_Qualifier = Split-Path -Path $env:FP -Qualifier 2^> $null;^
				if ($null -ne $FP_Qualifier) {^
					$FP_ProviderName = (Get-WMIObject -Class Win32_MappedLogicalDisk -Filter "DeviceID = '$FP_Qualifier'").ProviderName;^
					if ($null -ne $FP_ProviderName) {^
						$FP_NoQualifier = Split-Path -Path $env:FP -NoQualifier;^
						$FP_UNCPath = Join-Path -Path $FP_ProviderName -ChildPath $FP_NoQualifier;^
					}^
				}^
				if ($null -eq $FP_UNCPath) {^
					$FP = $env:FP;^
				} else {^
					$FP = $FP_UNCPath;^
				}^
				$FP_Base64 = [Convert]::ToBase64String([Text.Encoding]::UTF8.GetBytes($FP));^
				if ($null -ne $env:BatchArgs) {^
					$BatchArgs_Base64 = [Convert]::ToBase64String([Text.Encoding]::UTF8.GetBytes($env:BatchArgs));^
				}^
				$PS_RunAs_Args = '-NoProfile -Command ';^
				$PS_RunAs_Args += '$FP_Base64 = ' + "'$FP_Base64';";^
				$PS_RunAs_Args += '$BatchArgs_Base64 = ' + "'$BatchArgs_Base64';";^
				$PS_RunAs_Args += '$FP = [Text.Encoding]::UTF8.GetString([Convert]::FromBase64String($FP_Base64));';^
				$PS_RunAs_Args += 'if ($null -ne $BatchArgs_Base64) {';^
				$PS_RunAs_Args += '	$BatchArgs = [Text.Encoding]::UTF8.GetString([Convert]::FromBase64String($BatchArgs_Base64));';^
				$PS_RunAs_Args += '}';^
				$PS_RunAs_Args += '$Arg_S = ' + "$env:Arg_S;";^
				$PS_RunAs_Args += 'if (($Arg_S -eq 0) -and [bool]([System.Uri]$FP).IsUnc -and !(Test-Path -LiteralPath $FP -PathType Leaf)) {';^
				$PS_RunAs_Args += '	$cred = Get-Credential -Message "次にアクセスするための資格情報を入力してください:` $FP";';^
				$PS_RunAs_Args += '	New-PSDrive -Name TargetUNCPath -PSProvider FileSystem -Root (Split-Path -Path $FP -Parent) -Credential $cred;';^
				$PS_RunAs_Args += '}';^
				$PS_RunAs_Args += '$ArguList = ''"/s /c """"""'' + $FP + ''"""" '' + $BatchArgs + '' /R"""'';';^
				$PS_RunAs_Args += 'Start-Process -FilePath ' + "'$env:ComSpec'" + ' -ArgumentList $ArguList;';^
				Start-Process -WindowStyle Minimized -Verb RunAs -FilePath powershell -ArgumentList $PS_RunAs_Args;^
			}^
		} else {^
			$returnValue = 0;^
		}^
		exit $returnValue
	
	powershell -NoProfile -Command "Invoke-Expression -Command $env:PSCommand;"
	
exit /b

:exit1
	chcp %ACTIVE_CP% >nul

参考情報

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1