HowTo – Create an iso file using PowerShell Script

Hello World, 

Since the last post (Windows 10 – Refreshing Desktop wallpaper without logoff/logon (PowerShell script – Ver. 2.0)) was related to some powershell script, we have decided to check and share some additional scripts that might be helpful to others. We have not written the scripts presented below but they are so useful to us that we have decided to share them with you….

Initially, we were using a “simple” script that would help us create ISO file from a folder.  However, by preparing this post, we came across a more complete script that can generate a basic ISO file but offer some additional options like generating a bootable ISO file as well.   Since then, we are only using this script to perform this specific task….create an ISO File from Data contained in a folder….. 

Let’s quickly present the script and how to use it….. 

Overview 

Some customers does not allow us to use any software on their networks and the reason behind is to ensure or enforce security posture. Any software to be installed would need to be tested, validated and approved by the customer.   Since we have been working a lot on Virtualization projects lately (based on VMWare products),  it appears that some customers would need a way to copy data to their virtual machines.  One of the allowed way would be by uploading ISO images to datastores.  Once uploaded, the ISO could be mounted in the target virtual machines and the data could be copied over.  

Some people might mention the possibility to copy through the network using shared folders.  Again, based on specific scenario,  it was not always possible to transfer file over the network because firewall was blocking SMB traffic.   So, one of the few options available was to take advantage of the ISO format

Note :

It’s also possible to use Powercli cmdlet to transfer files between host and virtual machines (see copy-VMGuestFile). We might want to describe this other approach in another post….. 

The Script   

Credits

The script has not been written by us !! We have found the script on GitHub. The script can be found at the following location 

At the bottom of this post, you can retrieve the code source of the script as well  

How To use it  

Disclaimer

This script is provided AS-IS.  Use this script at your own risk !!!

How to Generate the ISO File

Step 1 –  You will need to copy/paste the script function code (code presented at the end of the post) into your PowerShell Console 

Click on Picture for Better Resolution

Step 2 –  From the PowerShell console, if the function has been loaded accordingly, you should be able to find the New-IsoFile cmdlet should be made available to you. You can check that the function is loaded by using the Get-Command Cmdlet (see screenshot below) 

Click on Picture for Better Resolution

Step 3 – Based on your needs, it’s time to generate the ISO File using the recently loaded function… Destination location and Target location should be different when using the script. Hereafter, you can see the basic usage of the function which will generate an ISO file and store it on the target location you have specified 

New-IsoFile -Source d:\Test -Path d:\test2.iso -Force

 

Click on Picture for Better Resolution

Note : More options are available with this script.  You could generate ISO file from Clipboard or you can create also bootable iso (as long as you have the necessary file installed on your machine).  Please read the information and example provided in the header of the script… 

Final Notes 

This is it for this quick post !   

If you ever need to generate some ISO File and there are not other tool available on your system, now, you know that you can use PowerShell and the provided function to generate one.   We hope that the information will be useful to others and remember use the script at your own risk !!!!  

Till next time 

See ya 

Annex  : The Script  

Credits and Source:  This script is a copy of the code provided at https://github.com/wikijm/PowerShell-AdminScripts/blob/master/Miscellaneous/New-IsoFile.ps1 

function New-IsoFile 
{ 
<# 
.Synopsis 
Creates a new .iso file 
.Description 
The New-IsoFile cmdlet creates a new .iso file containing content from chosen folders 
.Example 
New-IsoFile "c:\tools","c:Downloads\utils" 
This command creates a .iso file in $env:temp folder (default location) that contains c:\tools and c:\downloads\utils folders. 
The folders themselves are included at the root of the .iso image. 
.Example 
New-IsoFile -FromClipboard -Verbose 
Before running this command, select and copy (Ctrl-C) files/folders in Explorer first. 
.Example 
dir c:\WinPE | New-IsoFile -Path c:\temp\WinPE.iso -BootFile "${env:ProgramFiles(x86)}\Windows Kits\10\Assessment and Deployment Kit\Deployment Tools\amd64\Oscdimg\efisys.bin" -Media DVDPLUSR -Title "WinPE" 
This command creates a bootable .iso file containing the content from c:\WinPE folder, but the folder itself isn't included. 
Boot file etfsboot.com can be found in Windows ADK. 
Refer to IMAPI_MEDIA_PHYSICAL_TYPE enumeration for possible media types: 
http://msdn.microsoft.com/en-us/library/windows/desktop/aa366217(v=vs.85).aspx 
.Notes 
NAME: New-IsoFile 
AUTHOR: Chris Wu 
LASTEDIT: 03/23/2016 14:46:50 
#>

[CmdletBinding(DefaultParameterSetName='Source')]Param( 
[parameter(Position=1,Mandatory=$true,ValueFromPipeline=$true, ParameterSetName='Source')]$Source, 
[parameter(Position=2)][string]$Path = "$env:temp\$((Get-Date).ToString('yyyyMMdd-HHmmss.ffff')).iso", 
[ValidateScript({Test-Path -LiteralPath $_ -PathType Leaf})][string]$BootFile = $null, 
[ValidateSet('CDR','CDRW','DVDRAM','DVDPLUSR','DVDPLUSRW','DVDPLUSR_DUALLAYER','DVDDASHR','DVDDASHRW','DVDDASHR_DUALLAYER','DISK','DVDPLUSRW_DUALLAYER','BDR','BDRE')][string] $Media = 'DVDPLUSRW_DUALLAYER', 
[string]$Title = (Get-Date).ToString("yyyyMMdd-HHmmss.ffff"), 
[switch]$Force, 
[parameter(ParameterSetName='Clipboard')][switch]$FromClipboard 
) 

Begin { 
($cp = new-object System.CodeDom.Compiler.CompilerParameters).CompilerOptions = '/unsafe' 
if (!('ISOFile' -as [type])) { 
Add-Type -CompilerParameters $cp -TypeDefinition @'
public class ISOFile 
{ 
public unsafe static void Create(string Path, object Stream, int BlockSize, int TotalBlocks) 
{ 
int bytes = 0; 
byte[] buf = new byte[BlockSize]; 
var ptr = (System.IntPtr)(&bytes); 
var o = System.IO.File.OpenWrite(Path); 
var i = Stream as System.Runtime.InteropServices.ComTypes.IStream; 

if (o != null) { 
while (TotalBlocks-- > 0) { 
i.Read(buf, BlockSize, ptr); o.Write(buf, 0, bytes); 
} 
o.Flush(); o.Close(); 
} 
} 
} 
'@ 
} 

if ($BootFile) { 
if('BDR','BDRE' -contains $Media) { Write-Warning "Bootable image doesn't seem to work with media type $Media" } 
($Stream = New-Object -ComObject ADODB.Stream -Property @{Type=1}).Open() # adFileTypeBinary 
$Stream.LoadFromFile((Get-Item -LiteralPath $BootFile).Fullname) 
($Boot = New-Object -ComObject IMAPI2FS.BootOptions).AssignBootImage($Stream) 
} 

$MediaType = @('UNKNOWN','CDROM','CDR','CDRW','DVDROM','DVDRAM','DVDPLUSR','DVDPLUSRW','DVDPLUSR_DUALLAYER','DVDDASHR','DVDDASHRW','DVDDASHR_DUALLAYER','DISK','DVDPLUSRW_DUALLAYER','HDDVDROM','HDDVDR','HDDVDRAM','BDROM','BDR','BDRE') 

Write-Verbose -Message "Selected media type is $Media with value $($MediaType.IndexOf($Media))"
($Image = New-Object -com IMAPI2FS.MsftFileSystemImage -Property @{VolumeName=$Title}).ChooseImageDefaultsForMediaType($MediaType.IndexOf($Media)) 

if (!($Target = New-Item -Path $Path -ItemType File -Force:$Force -ErrorAction SilentlyContinue)) { Write-Error -Message "Cannot create file $Path. Use -Force parameter to overwrite if the target file already exists."; break } 
} 

Process { 
if($FromClipboard) { 
if($PSVersionTable.PSVersion.Major -lt 5) { Write-Error -Message 'The -FromClipboard parameter is only supported on PowerShell v5 or higher'; break } 
$Source = Get-Clipboard -Format FileDropList 
} 

foreach($item in $Source) { 
if($item -isnot [System.IO.FileInfo] -and $item -isnot [System.IO.DirectoryInfo]) { 
$item = Get-Item -LiteralPath $item
} 

if($item) { 
Write-Verbose -Message "Adding item to the target image: $($item.FullName)"
try { $Image.Root.AddTree($item.FullName, $true) } catch { Write-Error -Message ($_.Exception.Message.Trim() + ' Try a different media type.') } 
} 
} 
} 

End { 
if ($Boot) { $Image.BootImageOptions=$Boot } 
$Result = $Image.CreateResultImage() 
[ISOFile]::Create($Target.FullName,$Result.ImageStream,$Result.BlockSize,$Result.TotalBlocks) 
Write-Verbose -Message "Target image ($($Target.FullName)) has been created"
$Target
} 
}

 

 

One thought on “HowTo – Create an iso file using PowerShell Script

Leave a Reply