Skip to content

Instantly share code, notes, and snippets.

@JonnyTech
Last active August 13, 2023 20:29
Show Gist options
  • Save JonnyTech/0be66f6855ac206fdc0211474c6365bd to your computer and use it in GitHub Desktop.
Save JonnyTech/0be66f6855ac206fdc0211474c6365bd to your computer and use it in GitHub Desktop.
Create bootable Windows installer drive from Linux
#!/bin/bash
die(){
echo -e "\n$1"
echo -e "\nUsage: $0 /path/to/windows.iso /path/to/usb [gpt|mbr] [full|quick]\n"
exit
}
[ "$(id -u)" != "0" ] && die "You must be root to run this script"
[ -f "$1" ] && iso="$1" || die "Error: File $1 does not exist"
[ -e "$2" ] && usb="$2" || die "Error: Drive $2 not present"
[[ ${3,,} = "mbr" ]] && { mode=1; echo "Mode: MBR"; } || { mode=0; echo "Mode: GPT"; }
[[ ${4,,} = "full" ]] && { files=1; echo "Files: Full"; } || { files=0; echo "Files: Quick"; }
curl -LJO https://github.com/pbatard/rufus/raw/master/res/uefi/uefi-ntfs.img
umount "${usb}"?*
wipefs -fa "${usb}"
parted "${usb}" -s mklabel `[ $mode = 1 ] && echo msdos || echo gpt`
bs=`lsblk -bno log-sec "$usb" |head -1`
size=$(((`stat -c '%s' uefi-ntfs.img`+$bs-1)/$bs))
parted "${usb}" -s mkpart primary ntfs 4MiB -- -`[ $mode = 1 ] && echo $(($size+1)) || echo $(($size+1+33))`s
parted "${usb}" -a none -s mkpart primary fat16 -- -`[ $mode = 1 ] && echo $size || echo $(($size+33))`s -`[ $mode = 1 ] && echo 1 || echo $((1+33))`s
sync "${usb}"
mkntfs -v -Q -I -T -F -L "Windows_USB" "${usb}1"
tmpiso=$(mktemp /tmp/tmpisoXXXX -d)
tmpusb=$(mktemp /tmp/tmpusbXXXX -d)
mount --options loop,ro --types udf,iso9660 "${iso}" "${tmpiso}"
mount "${usb}1" "${tmpusb}"
if [ $files = 1 ]
then
rsync -aP "${tmpiso}"/ "${tmpusb}"
else
rsync -aP --exclude 'sources/install.wim' "${tmpiso}"/ "${tmpusb}"
touch "${tmpusb}"/sources/install.wim
fi
if [ $mode = 1 ]
then
grub-install --target=i386-pc --boot-directory="${tmpusb}" --force "${usb}"
echo -e "ntldr /bootmgr\nboot" > "${tmpusb}"/grub/grub.cfg
fi
umount "${tmpiso}" "${tmpusb}"
rm -rf "${tmpiso}" "${tmpusb}"
dd if=uefi-ntfs.img of="${usb}2"
unset -v iso usb mode bs size
@JonnyTech
Copy link
Author

Script has been updated, thank you @andrewdbate for testing and reporting back.

Changes:

  • supports both gpt and mbr schemes via optional argument
  • calculate offsets and sizes from downloaded uefi-ntfs.img file
  • added reserved space at end of GPT drive as per feedback

This is still untested (due to lack of hardware) so any further feedback is welcome.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment