Last active
January 22, 2022 19:50
Create bootable Windows installer (virtual) drive image from Linux
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
die(){ | |
echo -e "\n$1" | |
echo -e "\nUsage: $0 /path/to/windows.iso /path/to/output.img [gpt|mbr]\n" | |
exit | |
} | |
[ "$(id -u)" != "0" ] && die "You must be root to run this script" | |
[ -f "$1" ] && iso="$1" || die "Error: $1 does not exist" | |
[ ! -f "$2" ] && img="$2" || die "Error: $2 already exists" | |
[[ ${3,,} = "mbr" ]] && { mode=1; echo "Mode: MBR"; } || { mode=0; echo "Mode: GPT"; } | |
curl -LJO https://github.com/pbatard/rufus/raw/master/res/uefi/uefi-ntfs.img | |
fallocate -l 6GiB "$img" | |
parted "$img" -s mklabel `[ $mode = 1 ] && echo msdos || echo gpt` | |
loop=`losetup --partscan --show --find "$img"` | |
bs=`lsblk -bno log-sec "$loop" |head -1` | |
size=$(((`stat -c '%s' uefi-ntfs.img`+$bs-1)/$bs)) | |
parted "$img" -s mkpart primary ntfs 4MiB -- -`[ $mode = 1 ] && echo $(($size+1)) || echo $(($size+1+33))`s | |
parted "$img" -a none -s mkpart primary fat16 -- -`[ $mode = 1 ] && echo $size || echo $(($size+33))`s -`[ $mode = 1 ] && echo 1 || echo $((1+33))`s | |
losetup -d "$loop" | |
loop=`losetup --partscan --show --find "$img"` | |
mkntfs -Q -I -L "Windows_USB" "${loop}p1" | |
mkdir /tmp/iso /tmp/img | |
mount --options loop,ro --types udf,iso9660 "$iso" /tmp/iso | |
mount "${loop}p1" /tmp/img | |
rsync -Pr /tmp/iso/ /tmp/img | |
if [ $mode = 1 ] | |
then | |
grub-install --target=i386-pc --boot-directory=/tmp/img --force "$loop" | |
echo -e "ntldr /bootmgr\nboot" > /tmp/img/grub/grub.cfg | |
fi | |
umount /tmp/iso /tmp/img | |
rm -rf /tmp/iso /tmp/img | |
dd if=uefi-ntfs.img of="${loop}p2" | |
losetup -d "$loop" | |
# convert image file for use with virtualbox | |
vboxmanage convertfromraw --format vdi --variant fixed "$img" "$img.vdi" | |
unset -v iso img mode bs size loop |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Script to create drive image file for Windows installer - specify
mbr
orgpt
to partition accordingly.