Wednesday, March 28, 2012

PowerShell 7zip SFX Installer


  1. Save the below two scripts 
  2. Download 7zsd_All_x64.sfx
  3. 7z the 3 files together as 7z.7z, or at a minimum zip Setup.ps1 as 7z.7z
  4. Run 7zInstaller.ps1
  5. It will build a New.EXE then run the EXE.
  6. This will extract the files to a temp folder, and call a powerShell prompt that will run the Setup.PS1 and leave the prompt open.

Modify the Setup.ps1, remove the -NoExit argument, and you can use the script to move the files from the temp location to anywhere you need it.  When the powershell script finishes, the temp folder should be removed.

You can also specify an "InstallPath="path_to_extract"" in the SetupConfig block.  If you do this you don't have to manually copy the files and 7z will not delete the files.

Take a look at http://7zsfx.info/en/parameters.html it has a good collection of what options can be used in the SetupConfig block.  Of note, you can use environment variables, so you could extract directly to a user profile if you wanted to.

7zInstaller.ps1

001
002
003
004
005
006
007
008
009
010
011
012
013
014
015
016
017
018
019
020
021
022
023
024
025
026
027
028
029
030
031
032
033
034
035
036
037
038
039
040
041

# Script will not create the 7z file.
$ZipName= "7z.7z"
# Output SFX EXE
$OutName= "new.exe"

# This config data tells the SFX how you want to do things.
# Other than the initial popup, we push all the other options into the PS1.
# http://7zsfx.info/en/parameters.html
$SetupConfig = @"
;!@Install@!UTF-8!
Title="Title Spot"
BeginPrompt="Do you want to install now?"
RunProgram="powershell -NoExit -noprofile -executionpolicy unrestricted -file %%T\\Setup.PS1"
;!@InstallEnd@!
"@


# get from http://7zsfx.info/en/ this was pulled from the "7zSD extra" option.
# There are a selection of these that may display a console vs winforms UI, and
# may also switch between 32bit and 64bit extraction.
$SFX="7zsd_All_x64.sfx" #"7z.SFX"


# this name can be whatever. It will overwrite each time.
$ConfigName= "SetupConfig.txt"

# Need to Move PWD to scripting folder (This simplifies the below, everthing should work with full paths)
$path = $script:MyInvocation.MyCommand.Path
cd $path

$SetupConfig | out-File "$(Split-Path $path)\$ConfigName" -enc UTF8


# The first sample on Binary merges used ADD-Content. This is why I had to kill the file.
# Set-Content though in the same pipeline will append all of the data so we are good.
# The test-path and cleanup is just something nice to keep around.
if (Test-Path $OutName) { del $OutName }
get-content $SFX,$ConfigName,$ZipName -Enc Byte -Read 512 | set-content $OutName -Enc Byte

#Test the installer
Start-process $OutName


Setup.ps1:

001
002
003
Write-Host "Installer Script"
$script:MyInvocation.MyCommand | fl
ls env:7z*Folder*


Posted an update @ http://import-powershell.blogspot.com/2012/03/7z-sfx-without-temp-config-file.html