Skip to content

Instantly share code, notes, and snippets.

@kyle-herzog
Created November 10, 2012 23:40
Show Gist options
  • Save kyle-herzog/4053002 to your computer and use it in GitHub Desktop.
Save kyle-herzog/4053002 to your computer and use it in GitHub Desktop.
Powershell script to expand archive files using 7zip command line tools
function Expand-Item7zip
{
param
(
[Parameter(Mandatory=$true)] [string] $item,
[Parameter(Mandatory=$true)] [string] $destinationDirectory
)
if (!(Test-Path -Path $item -PathType Leaf))
{
throw ("Specified archive File is invalid: " + $item)
}
if (!(Test-Path -Path $destinationDirectory -PathType Container))
{
New-Item $destinationDirectory -ItemType Directory | Out-Null
}
if(!(Get-Command "7z" -ErrorAction SilentlyContinue))
{
$7zipInstallationDirectory = "C:\Program Files\7-Zip"
if(!(Confirm-64BitOS))
{
$7zipInstallationDirectory = "C:\Program Files (x86)\7-Zip"
}
Set-EnvironmentVariable -name "Path" -value $7zipInstallationDirectory -scope "session" -appendValue
}
#& "7z" l $item
$result = (& "7z" x "-o$destinationDirectory" "$item")
}
function Confirm-64BitOS
{
(Get-WmiObject -Class Win32_OperatingSystem).OSArchitecture -eq "64-bit"
}
function Set-EnvironmentVariable
{
param
(
[Parameter(Mandatory=$true)] [string] $name,
[Parameter(Mandatory=$true)] [string] $value,
[Parameter(Mandatory=$false)] [string] $scope = "process",
[switch] $appendValue
)
$scope = $scope.ToLower()
if(($scope -ne "machine") -and ($scope -ne "user") -and ($scope -ne "process"))
{
THROW New-Object System.Exception "Scope must be 'machine', 'user', or 'process'"
}
if($appendValue)
{
$newValue = (Get-Item "Env:\$name").Value
if(!$newValue.Contains($value))
{
$newValue += ";$value"
}
$value = $newValue
}
Set-Item -Path "Env:$name" -Value "$value"
[Environment]::SetEnvironmentVariable("$name", "$value", "$scope")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment