Skip to content

Instantly share code, notes, and snippets.

@altrive
Created September 8, 2013 19:15
Show Gist options
  • Select an option

  • Save altrive/6487560 to your computer and use it in GitHub Desktop.

Select an option

Save altrive/6487560 to your computer and use it in GitHub Desktop.
function Install-PSModule
{
[CmdletBinding()]
param(
[Parameter(Mandatory)]
[string] $ModuleName,
[Parameter(Mandatory,ParameterSetName="Local")]
[string] $Path,
[ValidateSet("User","System","ProgramFiles","Local")]
[string] $Target = "User"
)
$ErrorActionPreference = "Stop"
Set-StrictMode -Version Latest
if(!(Test-Path $Path -PathType Container)){
Write-Error ("Directory is not found! : {0}" -f $Path)
}
#Resolve target module base directory
switch($Target)
{
"Local"{
$moduleBasePath = Join-Path (Resolve-Path .) "Modules" #Use Current Directory
}
default{
$moduleBasePath = $env:PSModulePath.Split(";") | where {$_.StartsWith([Environment]::GetFolderPath($Target),[StringComparison]::InvariantCultureIgnoreCase)} | select -First 1
}
}
if([String]::IsNullOrEmpty($moduleBasePath)){
throw ("PowerShell module path is not found for target({0})" -f $Target)
}
#Set target module directory
$modulePath = Join-Path $moduleBasePath $ModuleName
#Change current directory to get relative path
Push-Location -Path $Path
try{
$items = Get-ChildItem -File -Recurse #Get files under current directory
Write-Verbose ("Install PowerShell module to '{0}'..." -f $modulePath)
foreach($item in $items)
{
#Relative path to CopyFrom basepath
$relativePath = Resolve-Path $item.FullName -Relative
#Copy file operation target path
$destination = Join-Path $modulePath $relativePath
#Create directory if not exist already
(New-Object IO.FileInfo($destination)).Directory.Create()
Write-Verbose ("`tCopy file '{0}'" -f $relativePath)
Copy-Item -Path $item.FullName -Destination $destination -Force
}
}
finally
{
Pop-Location -ErrorAction Ignore
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment