AdvancedInstaller生成后自动创建ISO虚拟光盘
添加属性
添加生成事件
C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe
-ExecutionPolicy RemoteSigned -File "d:\script\createiso.ps1" "[|AI_BUILD_OUTPUT_FOLDER]" "[|IsoFileName]" "[|IsoTitle]_[|ProductVersion]" "[|SystemType]"
@@#
效果图
脚 本如下
Param(
[string]$path,
[string]$iso,
[string]$title,
[string]$systemtype
)
# $path = "E:\advInstallerProjects\SystemHotfix\Setup Files"
# $iso="e:\shared\NetCoreSetup"
# $title="NetCoreSetup_Test"
# $systemtype="all"
Write-Host create `"$path`" to `"$iso`" with $title
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"),
[string]$Exclude = "",
[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 )){
# 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
}
$SystemType = $SystemType.ToLower()
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)"
# Write-Host "begin Adding item to the target image: $($item.FullName)"
try {
# $Image.Root.AddDirectory($item.Name)
if ([System.String]::IsNullOrEmpty($Exclude)){
$Image.Root.AddTree($item.FullName, $true)
}else{
# 再循环一层结构
if ($item -is [System.IO.DirectoryInfo]){
$Image.Root.AddDirectory($item.Name)
Get-ChildItem $item.FullName | ? { -not $_.PsIsContainer -or $_.FullName -notmatch $Exclude } | ForEach-Object -Process {
# Write-Host "add subPath by filter $Exclude : $($_.FullName)"
$Image.Root.Item($item.Name).AddTree($_.FullName, $true)
}
}else{
$Image.Root.AddTree($item.FullName, $true)
}
}
} catch {
Write-Error -Message ($_.Exception.Message.Trim() + ' Try a different media type.')
}
}
}
# 移除特定目录
foreach($d in $RemovePath){
# Write-Host "remove" $d
# $Image.Root.RemoveTree("Prerequisites")
}
}
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
}
}
Function read-HostTimeout {
###################################################################
## Description: Mimics the built-in "read-host" cmdlet but adds an expiration timer for
## receiving the input. Does not support -assecurestring
##
## This script is provided as is and may be freely used and distributed so long as proper
## credit is maintained.
##
## Written by: thegeek@thecuriousgeek.org
## Date Modified: 10-24-14
###################################################################
# Set parameters. Keeping the prompt mandatory
# just like the original
param(
[Parameter(Mandatory=$true,Position=1)]
[string]$prompt,
[Parameter(Mandatory=$false,Position=2)]
[int]$delayInSeconds
)
# Do the math to convert the delay given into milliseconds
# and divide by the sleep value so that the correct delay
# timer value can be set
$sleep = 250
$delay = ($delayInSeconds*1000)/$sleep
$count = 0
$charArray = New-Object System.Collections.ArrayList
Write-host -nonewline "$($prompt): "
# While loop waits for the first key to be pressed for input and
# then exits. If the timer expires it returns null
While ( (!$host.ui.rawui.KeyAvailable) -and ($count -lt $delay) ){
start-sleep -m $sleep
$count++
If ($count -eq $delay) { "`n"; return $null}
}
# Retrieve the key pressed, add it to the char array that is storing
# all keys pressed and then write it to the same line as the prompt
$key = $host.ui.rawui.readkey("NoEcho,IncludeKeyUp").Character
$charArray.Add($key) | out-null
Write-host -nonewline $key
# This block is where the script keeps reading for a key. Every time
# a key is pressed, it checks if it's a carriage return. If so, it exits the
# loop and returns the string. If not it stores the key pressed and
# then checks if it's a backspace and does the necessary cursor
# moving and blanking out of the backspaced character, then resumes
# writing.
$key = $host.ui.rawui.readkey("NoEcho,IncludeKeyUp")
While ($key.virtualKeyCode -ne 13) {
If ($key.virtualKeycode -eq 8) {
$charArray.Add($key.Character) | out-null
Write-host -nonewline $key.Character
$cursor = $host.ui.rawui.get_cursorPosition()
write-host -nonewline " "
$host.ui.rawui.set_cursorPosition($cursor)
$key = $host.ui.rawui.readkey("NoEcho,IncludeKeyUp")
}
Else {
$charArray.Add($key.Character) | out-null
Write-host -nonewline $key.Character
$key = $host.ui.rawui.readkey("NoEcho,IncludeKeyUp")
}
}
""
$finalString = -join $charArray
return $finalString
}
Function create($delayInSeconds,$subType,$Exclude){
Write-Host "begin create $subType ,please wait..."
try
{
if ([System.String]::IsNullOrEmpty($subType)){
$isoFileName = $iso + ".iso"
}else{
$isoFileName = $iso + "_$subType.iso"
}
Get-ChildItem $path | New-IsoFile -path $isoFileName -Title $title -Exclude $Exclude -Force -ErrorAction Stop
Write-Host "ok" -ForegroundColor Yellow
[System.Diagnostics.Process]::Start([System.IO.Path]::GetDirectoryName($iso))
}
catch
{
Write-Warning "Error: $_"
# 远程桌面切换为导致产生很多水平定位符
try{
$retry = read-HostTimeout -prompt "请在 $delayInSeconds 秒内进行选择:1 重试 0 退出" -delayInSeconds $delayInSeconds
$retry= $retry.Replace("`t","").Replace("`0","").Replace(" ","").Trim()
# Write-Host `"$retry`"
#[System.IO.File]::WriteAllText("aa.bin",$retry.Replace("`t","").Replace("`0","").Trim())
if($retry -eq "1"){
Write-Host "`n重新生成..." -ForegroundColor Yellow
create -delayInSeconds $delayInSeconds
}
}catch{
#Write-Warning "Error: $_"
pause
}
# Choice /C yn /D n /t 30 /m "是否重试? "
#if ($LASTEXITCODE -eq "1") # 1 for "yes" 2 for "no"
# {
# Write-Host "重新生成..." -ForegroundColor Yellow create
# }
}
}
# 备份可能 的文件
if( [System.IO.File]::Exists($iso) ){
# Write-Host "backup"
# [System.IO.File]::Copy($iso,$iso+".bak",1 )
# [System.IO.File]::Delete($iso)
}
$systemtype = $systemtype.ToLower()
#判断类型与目录 full 全部类型 all 全部子类型和全部类型 windows7 只包含该类型
$reg= "windows\s*\d+\.?\d*"
if ($systemtype -eq "full" -or $systemtype -eq "all"){
# 生成一个包含所有操作系统文件的光盘
create -delayInSeconds 60 -subType "full" -Exclude ""
}
# 查找所有操作系统类型,依次处理,简单处理下名称,因为是自己创建的目录,尽量遵循windowsN.M的规则,不要掺杂其它字符
[System.Collections.Generic.List[string]] $windowsList={}
$windowsList.Clear()
Get-ChildItem -Path $path -r | ? { $_.PsIsContainer -and $_.FullName -match $reg } | ForEach-Object -Process {
if(-not $windowsList.Contains($Matches[0].ToLower().Replace(" ","")))
{
$windowsList.Add($Matches[0].ToLower().Replace(" ",""))
}
}
if ($systemtype -eq "all"){
create -delayInSeconds 60 -subType "" -Exclude $reg
}
foreach($win in $windowsList){
if ($systemtype -eq "all" -or $systemtype -eq $win){
# 排除其它操作系统 :包含其它,排他当前(因为创建ISO时是排除匹配的目录)
$regNew = "("+ [System.String]::Join(")|(",$windowsList.Where{ -not ( $_ -eq $win ) } ) +")"
$regNew =$regNew.Replace("windows","windows\s*")
create -delayInSeconds 60 -subType $win -Exclude $regNew
}
}
# & timeout /T 5 /NOBREAK
# open
@@#