Unpacking Software Livestream

Join our monthly Unpacking Software livestream to hear about the latest news, chat and opinion on packaging, software deployment and lifecycle management!

Learn More

Chocolatey Product Spotlight

Join the Chocolatey Team on our regular monthly stream where we put a spotlight on the most recent Chocolatey product releases. You'll have a chance to have your questions answered in a live Ask Me Anything format.

Learn More

Chocolatey Coding Livestream

Join us for the Chocolatey Coding Livestream, where members of our team dive into the heart of open source development by coding live on various Chocolatey projects. Tune in to witness real-time coding, ask questions, and gain insights into the world of package management. Don't miss this opportunity to engage with our team and contribute to the future of Chocolatey!

Learn More

Calling All Chocolatiers! Whipping Up Windows Automation with Chocolatey Central Management

Webinar from
Wednesday, 17 January 2024

We are delighted to announce the release of Chocolatey Central Management v0.12.0, featuring seamless Deployment Plan creation, time-saving duplications, insightful Group Details, an upgraded Dashboard, bug fixes, user interface polishing, and refined documentation. As an added bonus we'll have members of our Solutions Engineering team on-hand to dive into some interesting ways you can leverage the new features available!

Watch On-Demand
Chocolatey Community Coffee Break

Join the Chocolatey Team as we discuss all things Community, what we do, how you can get involved and answer your Chocolatey questions.

Watch The Replays
Chocolatey and Intune Overview

Webinar Replay from
Wednesday, 30 March 2022

At Chocolatey Software we strive for simple, and teaching others. Let us teach you just how simple it could be to keep your 3rd party applications updated across your devices, all with Intune!

Watch On-Demand
Chocolatey For Business. In Azure. In One Click.

Livestream from
Thursday, 9 June 2022

Join James and Josh to show you how you can get the Chocolatey For Business recommended infrastructure and workflow, created, in Azure, in around 20 minutes.

Watch On-Demand
The Future of Chocolatey CLI

Livestream from
Thursday, 04 August 2022

Join Paul and Gary to hear more about the plans for the Chocolatey CLI in the not so distant future. We'll talk about some cool new features, long term asks from Customers and Community and how you can get involved!

Watch On-Demand
Hacktoberfest Tuesdays 2022

Livestreams from
October 2022

For Hacktoberfest, Chocolatey ran a livestream every Tuesday! Re-watch Cory, James, Gary, and Rain as they share knowledge on how to contribute to open-source projects such as Chocolatey CLI.

Watch On-Demand

Downloads:

1,363

Downloads of v 3.0.0:

329

Last Update:

18 Jun 2016

Package Maintainer(s):

Software Author(s):

  • Jayme Edwards

Tags:

admin

PowerDelivery 3

This is not the latest version of PowerDelivery 3 available.

  • 1
  • 2
  • 3

3.0.0 | Updated: 18 Jun 2016

Downloads:

1,363

Downloads of v 3.0.0:

329

Maintainer(s):

Software Author(s):

  • Jayme Edwards

Tags:

admin

PowerDelivery 3 3.0.0

This is not the latest version of PowerDelivery 3 available.

  • 1
  • 2
  • 3

All Checks are Passing

3 Passing Tests


Validation Testing Passed


Verification Testing Passed

Details

Scan Testing Successful:

No detections found in any package files

Details
Learn More

Deployment Method: Individual Install, Upgrade, & Uninstall

To install PowerDelivery 3, run the following command from the command line or from PowerShell:

>

To upgrade PowerDelivery 3, run the following command from the command line or from PowerShell:

>

To uninstall PowerDelivery 3, run the following command from the command line or from PowerShell:

>

Deployment Method:

NOTE

This applies to both open source and commercial editions of Chocolatey.

1. Enter Your Internal Repository Url

(this should look similar to https://community.chocolatey.org/api/v2/)


2. Setup Your Environment

1. Ensure you are set for organizational deployment

Please see the organizational deployment guide

2. Get the package into your environment

  • Open Source or Commercial:
    • Proxy Repository - Create a proxy nuget repository on Nexus, Artifactory Pro, or a proxy Chocolatey repository on ProGet. Point your upstream to https://community.chocolatey.org/api/v2/. Packages cache on first access automatically. Make sure your choco clients are using your proxy repository as a source and NOT the default community repository. See source command for more information.
    • You can also just download the package and push it to a repository Download

3. Copy Your Script

choco upgrade powerdelivery3 -y --source="'INTERNAL REPO URL'" --version="'3.0.0'" [other options]

See options you can pass to upgrade.

See best practices for scripting.

Add this to a PowerShell script or use a Batch script with tools and in places where you are calling directly to Chocolatey. If you are integrating, keep in mind enhanced exit codes.

If you do use a PowerShell script, use the following to ensure bad exit codes are shown as failures:


choco upgrade powerdelivery3 -y --source="'INTERNAL REPO URL'" --version="'3.0.0'" 
$exitCode = $LASTEXITCODE

Write-Verbose "Exit code was $exitCode"
$validExitCodes = @(0, 1605, 1614, 1641, 3010)
if ($validExitCodes -contains $exitCode) {
  Exit 0
}

Exit $exitCode

- name: Install powerdelivery3
  win_chocolatey:
    name: powerdelivery3
    version: '3.0.0'
    source: INTERNAL REPO URL
    state: present

See docs at https://docs.ansible.com/ansible/latest/modules/win_chocolatey_module.html.


chocolatey_package 'powerdelivery3' do
  action    :install
  source   'INTERNAL REPO URL'
  version  '3.0.0'
end

See docs at https://docs.chef.io/resource_chocolatey_package.html.


cChocoPackageInstaller powerdelivery3
{
    Name     = "powerdelivery3"
    Version  = "3.0.0"
    Source   = "INTERNAL REPO URL"
}

Requires cChoco DSC Resource. See docs at https://github.com/chocolatey/cChoco.


package { 'powerdelivery3':
  ensure   => '3.0.0',
  provider => 'chocolatey',
  source   => 'INTERNAL REPO URL',
}

Requires Puppet Chocolatey Provider module. See docs at https://forge.puppet.com/puppetlabs/chocolatey.


4. If applicable - Chocolatey configuration/installation

See infrastructure management matrix for Chocolatey configuration elements and examples.

Package Approved

This package was approved by moderator dtgm on 20 Jun 2016.

Description

Inspired by ansible and rails, powerdelivery organizes everything Windows PowerShell can do within a secure, convention-based framework so you can stop being jealous of your linux friends when you deploy to Windows.


tools\chocolateyInstall.ps1
<# ChocolateyInstall.ps1

Installs PowerDelivery3 with chocolatey.
#>

$ErrorActionPreference = 'Stop'

$moduleDir = Split-Path -parent $MyInvocation.MyCommand.Definition

. (Join-Path $moduleDir 'chocolateyPowerDeliveryUtils.ps1')

Install-PowerDeliveryModule -moduleDir $moduleDir -moduleName PowerDelivery -packageId powerdelivery3
tools\chocolateyPowerDeliveryUtils.ps1
<# chocolateyPowerDeliveryUtils.ps1

Installs and Uninstalls PowerShell modules for PowerDelivery with chocolatey.
#>

$ErrorActionPreference = 'Stop'

function Install-PowerDeliveryModule {
  [CmdletBinding()]
  param(
    [Parameter(Position=0, Mandatory=1)][string] $moduleDir,
    [Parameter(Position=1, Mandatory=1)][string] $moduleName,
    [Parameter(Position=2, Mandatory=1)][string] $packageId
  )
  
  $moduleDir = "$moduleDir\"

  $psModulePath = [Environment]::GetEnvironmentVariable("PSMODULEPATH", [EnvironmentVariableTarget]::Machine)

  $newEnvVar = $moduleDir

  $caseInsensitive = [StringComparison]::InvariantCultureIgnoreCase

  $pathSegment = "chocolatey\lib\$packageId\"

  if (![String]::IsNullOrWhiteSpace($psModulePath)) {
    if ($psModulePath.IndexOf($pathSegment, $caseInsensitive) -lt 0) { # First time installing
        if ($psModulePath.EndsWith(";")) {
            $psModulePath = $psModulePath.TrimEnd(";")
        }
        $newEnvVar = "$($psModulePath);$($moduleDir)"
    }
    else { # Replacing an existing install
        $indexOfSegment = $psModulePath.IndexOf($pathSegment, $caseInsensitive)
        $startingSemicolon = $psModulePath.LastIndexOf(";", $indexOfSegment, $caseInsensitive)
        $trailingSemicolon = $psModulePath.IndexOf(";", $indexOfSegment + $pathSegment.Length, $caseInsensitive)

        if ($startingSemicolon -ne -1) {
            $psModulePrefix = $psModulePath.Substring(0, $startingSemicolon)
            $newEnvVar = "$($psModulePrefix);$($moduleDir)"
        }     
        if ($trailingSemicolon -ne -1) {
            $newEnvVar += $psModulePath.Substring($trailingSemicolon)
        }
    }
  }
  else {
    $newEnvVar = "%PSMODULEPATH%;$newEnvVar"
  }

  [Environment]::SetEnvironmentVariable("PSMODULEPATH", $newEnvVar, [EnvironmentVariableTarget]::Machine)
  $Env:PSMODULEPATH = $newEnvVar

  Import-Module $moduleName -Force
}

function Uninstall-PowerDeliveryModule {
  [CmdletBinding()]
  param(
    [Parameter(Position=0, Mandatory=1)][string] $moduleDir,
    [Parameter(Position=1, Mandatory=1)][string] $moduleName,
    [Parameter(Position=2, Mandatory=1)][string] $packageId
  )

  try {
    Remove-Module $moduleName | Out-Null
  }
  catch {}

  $moduleDir = "$moduleDir\"

  $psModulePath = [Environment]::GetEnvironmentVariable("PSMODULEPATH", [EnvironmentVariableTarget]::Machine)

  $newEnvVar = $moduleDir

  $caseInsensitive = [StringComparison]::InvariantCultureIgnoreCase

  $pathSegment = "chocolatey\lib\$packageId\"

  if (![String]::IsNullOrWhiteSpace($psModulePath)) {
    if ($psModulePath.IndexOf($pathSegment, $caseInsensitive) -ge 0) {
        $indexOfSegment = $psModulePath.IndexOf($pathSegment, $caseInsensitive)
        $startingSemicolon = $psModulePath.LastIndexOf(";", $indexOfSegment, $caseInsensitive)
        $trailingSemicolon = $psModulePath.IndexOf(";", $indexOfSegment + $pathSegment.Length, $caseInsensitive)

        if ($startingSemicolon -ne -1) {
            $newEnvVar = $psModulePath.Substring(0, $startingSemicolon)
        }     
        if ($trailingSemicolon -ne -1) {
            $newEnvVar += $psModulePath.Substring($trailingSemicolon)
        }

        [Environment]::SetEnvironmentVariable("PSMODULEPATH", $newEnvVar, [EnvironmentVariableTarget]::Machine)
        $Env:PSMODULEPATH = $newEnvVar
    }
  }
}
tools\chocolateyUninstall.ps1
<# ChocolateyUninstall.ps1

Uninstalls PowerDelivery3 with chocolatey.
#>

$ErrorActionPreference = 'Stop'

$moduleDir = Split-Path -parent $MyInvocation.MyCommand.Definition

. (Join-Path $moduleDir 'chocolateyPowerDeliveryUtils.ps1')

Uninstall-PowerDeliveryModule -moduleDir $moduleDir -moduleName PowerDelivery -packageId powerdelivery3
tools\init.ps1
<# Init.ps1

Initializes PowerDelivery3 when loaded by chocolatey.
#>

param($installPath, $toolsPath, $package)

$modulePath = Join-Path $toolsPath PowerDelivery.psm1
Import-Module $modulePath -Force
tools\PowerDelivery\Cmdlets\Enter-DeliveryRole.ps1
function Enter-DeliveryRole {
  [CmdletBinding()]
  param(
    [Parameter(Position=0, Mandatory=1)][scriptblock] $Up,
    [Parameter(Position=1, Mandatory=0)][scriptblock] $Down
  )
  $fullPath = [System.IO.Path]::GetDirectoryName($MyInvocation.PSCommandPath)
  $roleName = [System.IO.Path]::GetFileName($fullPath)

  $pow.roles.Add($roleName, @($Up, $Down))
}

Set-Alias Delivery:Role Enter-DeliveryRole
Export-ModuleMember -Function Enter-DeliveryRole -Alias Delivery:Role
tools\PowerDelivery\Cmdlets\Invoke-MSBuild.ps1
<#
.Synopsis
Compiles a project using msbuild.exe.

.Description
The Invoke-MSBuild cmdlet is used to compile a MSBuild-compatible project or solution. You should always use this cmdlet instead of a direct call to msbuild.exe or existing cmdlets you may have found online when working with powerdelivery.

This cmdlet provides the following essential continuous delivery features:

Updates the version of any AssemblyInfo.cs (or AssemblyInfo.vb) files with the current build version. This causes all of your binaries to have the build number. For example, if your build pipeline's version in the script is set to 1.0.2 and this is a build against changeset C234, the version of your assemblies will be set to 1.0.2.234.

Automatically targets a build configuration matching the environment name ("Development", "Test", or "Production"). Create build configurations named "Development", "Test", and "Production" with appropriate settings in your projects for this to work. If you don't want this, you'll have to explicitly pass the configuration as a parameter.

Reports the status of the compilation back to TFS to be viewed in the build summary. This is important because it allows tests run using mstest.exe to have their run results associated with the compiled assets created using this cmdlet.

.Example
Invoke-MSBuild MyProject/MySolution.sln -properties  @{MyCustomProp = SomeValue}

.Parameter projectFile
A relative path at or below the script directory that specifies an MSBuild project or solution to compile.

.Parameter properties
Optional. A PowerShell hash containing name/value pairs to set as MSBuild properties.

.Parameter target
Optional. The name of the MSBuild target to invoke in the project file. Defaults to the default target specified within the project file.

.Parameter toolsVersion
Optional. The version of MSBuild to run ("2.0", "3.5", "4.0", etc.). The default is "4.0".

.Parameter verbosity
Optional. The verbosity of this MSBuild compilation. The default is "m".

.Parameter buildConfiguration
Optional. The default is to use the same as the environment name. Create build configurations named "Development", "Test", and "Production" with appropriate settings in your projects.

.Parameter flavor
Optional. The platform configuration (x86, x64 etc.) of this MSBuild complation. The default is "AnyCPU".

.Parameter ignoreProjectExtensions
Optional. A semicolon-delimited list of project extensions (".smproj;.csproj" etc.) of projects in the solution to not compile.
#>
function Invoke-MSBuild
{
  [CmdletBinding()]
  param(
    [Parameter(Position=0,Mandatory=1)][string] $projectFile, 
    [Parameter(Position=1,Mandatory=0)] $properties = @{}, 
    [Parameter(Position=2,Mandatory=0)][string] $target, 
    [Parameter(Position=3,Mandatory=0)][string] $toolsVersion = '4.0', 
    [Parameter(Position=4,Mandatory=0)][string] $verbosity = "m", 
    [Parameter(Position=5,Mandatory=0)][string] $buildConfiguration, 
    [Parameter(Position=6,Mandatory=0)][string] $flavor = "AnyCPU", 
    [Parameter(Position=7,Mandatory=0)][string] $ignoreProjectExtensions
  )

  if ([String]::IsNullOrWhiteSpace($buildConfiguration))
  {
    if ($pow.EnvironmentName -eq 'Local')
    {
		  $buildConfiguration = 'Debug'
    }
    else
    {
      $buildConfiguration = 'Release'
    }

    if (!$properties.ContainsKey('Configuration'))
    {
      $properties.Add('Configuration', $buildConfiguration)
    }
  }
  else
  {
    $properties.Add('Configuration', $buildConfiguration)
  }

  $regKey = "HKLM:\Software\Microsoft\MSBuild\ToolsVersions\$toolsVersion"
  $regProperty = "MSBuildToolsPath"
  $regKeyProperty = $null

  try
  {
    $regKeyProperty = (Get-ItemProperty $regKey)
  }
  catch
  {
    Write-Host ".NET ToolsVersion $toolsVersion not found in the registry. Is this version not installed?"
    throw 
  }

  $msbuildExe = Join-Path -path $regKeyProperty.$regProperty -childpath "msbuild.exe"

  $msBuildCommand = """$msbuildExe"""
  $msBuildCommand += " /nologo /m"

  if ($properties.length -gt 0)
  {  
    $properties.Keys | % {
      $msBuildCommand += " ""/p:$($_)=$($properties.Item($_))"""
    }
  }
	
  if ([string]::IsNullOrWhiteSpace($toolsVersion) -eq $false)
  {
    $msBuildCommand += " ""/tv:$toolsVersion"""
  }

  $msBuildCommand += " `"/consoleloggerparameters:Verbosity=q`""

  if ([string]::IsNullOrWhiteSpace($verbosity) -eq $false)
  {
    $msBuildCommand += " /v:$verbosity"
  }

  if ([string]::IsNullOrWhiteSpace($ignoreProjectExtensions) -eq $false)
  {
      $msBuildCommand += " ""/ignore:$ignoreProjectExtensions"""
  }

	if (![string]::IsNullOrWhiteSpace($target))
  {
		$msBuildCommand += " ""/T:$target"""
	}

  $currentDirectory = Get-Location

  $shortPath = [IO.Path]::GetDirectoryName($projectFile)
  $fullPath = Join-Path $currentDirectory $shortPath
  $fullPathNormalized = [IO.Path]::GetFullPath($fullPath)

  $projectFileName = [IO.Path]::GetFileName($projectFile)
  $fullProjectFile = Join-Path $fullPathNormalized $projectFileName
  $projectFileBase = [IO.Path]::GetFileNameWithoutExtension($projectFileName)
  $logFile = Join-Path $fullPathNormalized "$($projectFileBase).log"

  $msBuildCommand += " ""/l:FileLogger,Microsoft.Build.Engine;logfile=$logFile"""
  $msBuildCommand += " ""$fullProjectFile"""

  #Update-AssemblyInfoFiles -path $shortPath

  Set-Location $fullPathNormalized

  Invoke-Expression "& $msBuildCommand" | Out-Null

  if ($lastexitcode -ne 0)
  {
    $errorMessage = "Invoke-MSBuild failed. Check your parameters or try again with verbose output." 

    if (![String]::IsNullOrWhitespace($logFile))
    {
      $errorMessage += " See $logFile for details."
    }
    
    throw $errorMessage
  }
}

Export-ModuleMember -Function Invoke-MSBuild
tools\PowerDelivery\Cmdlets\New-DeliveryCredential.ps1
<#
.Synopsis
Encrypts a set of credentials with a key and adds them to a powerdelivery project.

.Description
Encrypts a set of credentials with a key and adds them to a powerdelivery project.

.Example
New-DeliveryCredentials MyKey "MYDOMAIN\myuser"

The credential will be created at the path:

.\Secrets\<KeyName>\Credentials\<UserName>.credential

.Parameter KeyName
The name of the key to use for encryption.

.Parameter UserName
The username of the account to encrypt the password for.

.Parameter Force
Switch that forces overwrite of any existing credential file if found.
#>
function New-DeliveryCredential {
  [CmdletBinding()]
  param (
    [Parameter(Position=0,Mandatory=1)][string] $KeyName,
    [Parameter(Position=1,Mandatory=1)][string] $UserName,
    [Parameter(Position=2,Mandatory=0)][switch] $Force
  )

  $projectDir = GetProjectDirectory

  ValidateNewFileName -FileName $SecretName -Description "secret name"
  
  $keyBytes = GetKeyBytes -ProjectDir $projectDir -KeyName $KeyName -ThrowOnError

  $credentialsPath = Join-Path (Get-Location) "Credentials\$KeyName"
  if (!(Test-Path $credentialsPath)) {
    New-Item $credentialsPath -ItemType Directory | Out-Null
  }

  $userNameFile = "$($UserName -replace '\\', '#').credential"
  $userNamePath = Join-Path $credentialsPath $userNameFile

  if ((Test-Path $userNamePath) -and (!$Force)) {
    throw "Credential at $userNamePath exists. Pass -Force to overwrite."
  }

  Write-Host "Enter the password for $userName and press ENTER:"
  try {
    Read-Host -AsSecureString | ConvertFrom-SecureString -Key $keyBytes | Out-File $userNamePath -Force
    Write-Host "Credential written to "".\Credentials\$keyName\$userNameFile"""
  }
  catch {
    "Key $KeyName appears to be invalid - $_"
  }
}

Export-ModuleMember -Function New-DeliveryCredential
tools\PowerDelivery\Cmdlets\New-DeliveryKey.ps1
<#
.Synopsis
Generates a powerdelivery key file used to encrypt credentials.

.Description
Generates a powerdelivery key file used to encrypt credentials.

The key will be created at the path:

<Drive>:\Users\<User>\Documents\PowerDelivery\Keys\<Project>\<KeyName>.key

.Example
New-DeliveryKey MyKey

.Parameter KeyName
The name of the key to generate.
#>
function New-DeliveryKey {
  [CmdletBinding()]
  param(
    [Parameter(Position=0,Mandatory=1)][string] $KeyName
  )

  ValidateNewFileName -FileName $KeyName -Description "key name"
  $projectDir = GetProjectDirectory
  $projectName = [IO.Path]::GetFileName($projectDir)

  $keyString = GetNewKey

  $myDocumentsFolder = GetMyDocumentsFolder
  $keysFolderPath = Join-Path $myDocumentsFolder "PowerDelivery\Keys\$projectName"
  $keyFilePath = Join-Path $keysFolderPath "$KeyName.key"

  if (Test-Path $keyFilePath) {
    throw "Key $keyFilePath already exists."
  }

  if (!(Test-Path $keysFolderPath)) {
    New-Item $keysFolderPath -ItemType Directory | Out-Null
  }

  $keyString | Out-File -FilePath $keyFilePath

  Write-Host "Key written to ""$keyFilePath"""
}

Export-ModuleMember -Function New-DeliveryKey
tools\PowerDelivery\Cmdlets\New-DeliveryProject.ps1
<#
.Synopsis
Creates a new powerdelivery project.

.Description
The New-DeliveryProject cmdlet generates the files needed to work with powerdelivery.

.Example
New-DeliveryProject MyApp 'Local', 'Test', 'Production'

.Parameter ProjectName
The name of the project to create.

.Parameter Environments
An array of the names of environments to create configuration variable and environment scripts for.
#>
function New-DeliveryProject {
  [CmdletBinding()]
  param (
    [Parameter(Position=0,Mandatory=1)][Alias('p')][string] $ProjectName,
    [Parameter(Position=1,Mandatory=0)][Alias('e')] $Environments
  )

  ValidateNewFileName -FileName $ProjectName -Description "project name"

  if ($Environments -ne $null) {
    foreach ($environment in $Environments) {
      ValidateNewFileName -FileName $environment -Description "environment name"
    }
  }

  $templatesPath = Join-Path $pow.scriptDir "Templates"

  $projectDir = "$($ProjectName)Delivery"

  if (Test-Path $projectDir) {
    throw "Directory $projectDir already exists."
  }

  $configurationDir = "$projectDir\Configuration"
  $environmentsDir = "$projectDir\Environments"
  $rolesDir = "$projectDir\Roles"
  $secretsDir = "$projectDir\Secrets"
  $targetsDir = "$projectDir\Targets"

  $dirsToCreate = @($configurationDir, $secretsDir, $environmentsDir, $rolesDir, $targetsDir)

  # Create directories
  foreach ($dirToCreate in $dirsToCreate) {
    New-Item $dirToCreate -ItemType Directory | Out-Null
  }

  # Copy the default target script
  Copy-Item "$templatesPath\Target.ps1.template" "$targetsDir\Release.ps1"

  # Copy the shared configuration variables script
  Copy-Item "$templatesPath\_Shared.ps1.template" "$configurationDir\_Shared.ps1"

  if ($Environments -ne $null) {
    foreach ($environment in $Environments) {

      # Copy the environment configuration variables script
      Copy-Item "$templatesPath\Configuration.ps1.template" "$configurationDir\$environment.ps1"

      # Copy the environment nodes script
      Copy-Item "$templatesPath\Environment.ps1.template" "$environmentsDir\$environment.ps1"
    }
  }

  Write-Host "Project successfully created at "".\$($ProjectName)Delivery"""
}

Export-ModuleMember -Function New-DeliveryProject
tools\PowerDelivery\Cmdlets\New-DeliveryRole.ps1
<#
.Synopsis
Generates a new powerdelivery role.

.Description
Generates a new powerdelivery role.

The role will be created at the path:

.\Roles\<RoleName>

.Example
New-DeliveryRole Database

.Parameter RoleNames
A comma-separated list of one or more names of roles to create.
#>
function New-DeliveryRole {
  param(
    [Parameter(Position=1,Mandatory=1)][string[]] $RoleName
  )

  $projectDir = GetProjectDirectory

  ValidateNewFileName -FileName $RoleName -Description "role name"

  $templatesPath = Join-Path $pow.scriptDir "Templates"

  foreach ($role in $RoleName) {

    $rolePath = ".\Roles\$role"
    $roleDir = Join-Path $projectDir "Roles\$role"
    $migrationsDir = Join-Path $roleDir "Migrations"

    if (Test-Path $roleDir) {
      throw "Directory $rolePath already exists."
    }

    New-Item $migrationsDir -ItemType Directory | Out-Null

    # Copy the role script
    Copy-Item "$templatesPath\Role.ps1.template" "$roleDir\Always.ps1"

    Write-Host "Role created at ""$rolePath"""
  }
}

Export-ModuleMember -Function New-DeliveryRole
tools\PowerDelivery\Cmdlets\New-DeliverySecret.ps1
<#
.Synopsis
Encrypts a secret with a key and adds it to to a powerdelivery project.

.Description
Encrypts a secret with a key and adds it to to a powerdelivery project.

The secret will be created at the path:

.\Secrets\<KeyName>\<SecretName>.secret

.Example
New-DeliverySecret MyKey MySecret

.Parameter KeyName
The name of the key to use for encryption.

.Parameter SecretName
The name of the secret to encrypt.

.Parameter Force
Switch that forces overwrite of any existing secret file if found.
#>
function New-DeliverySecret {
  [CmdletBinding()]
  param (
    [Parameter(Position=0,Mandatory=1)][string] $KeyName,
    [Parameter(Position=1,Mandatory=1)][string] $SecretName,
    [Parameter(Position=2,Mandatory=0)][switch] $Force
  )

  $projectDir = GetProjectDirectory

  ValidateNewFileName -FileName $SecretName -Description "secret name"
  
  $keyBytes = GetKeyBytes -ProjectDir $projectDir -KeyName $KeyName -ThrowOnError

  $secretsPath = Join-Path (Get-Location) "Secrets\$KeyName"
  if (!(Test-Path $secretsPath)) {
    New-Item $secretsPath -ItemType Directory | Out-Null
  }

  $secretFile = "$(SecretName).secret"
  $secretPath = Join-Path $secretsPath $secretFile 
  if ((Test-Path $secretPath) -and (!$Force)) {
    throw "Secret at $secretPath exists. Pass -Force to overwrite."
  }

  Write-Host "Enter the secret value $SecretKey and press ENTER:"
  try {
    Read-Host -AsSecureString | ConvertFrom-SecureString -Key $keyBytes | Out-File $secretPath -Force
    Write-Host "Secret written to "".\Secrets\$KeyName\$secretFile"""
  }
  catch {
    "Key $KeyName appears to be invalid - $_"
  }
}

Export-ModuleMember -Function New-DeliverySecret
tools\PowerDelivery\Cmdlets\Publish-DeliveryFilesToAzure.ps1
<#
.Synopsis
Uploads files for a powerdelivery release to Windows Azure for use by nodes that will host the product.

.Description
Uploads files for a powerdelivery release to Windows Azure for use by nodes that will host the product. 
All files that are uploaded are prefixed with a path that contains the name of the powerdelivery project and a 
timestamp of the date and time that the target started.

.Example
Delivery:Role {
  param($target, $config, $node)
  
  # Recursively uploads files within the folder "MyApp\bin\Release" to a Windows Azure 
  # storage container below a <ProjectName>\<StartedAt> path.
  Publish-DeliveryFilesToAzure -Path "MyApp\bin\Debug" `
                               -Destination "MyApp" `
                               -Credential $target.Credentials['[email protected]'] `
                               -SubscriptionId $config.MyAzureSubsciptionId `
                               -StorageAccountName $config.MyAzureStorageAccountName `
                               -StorageAccountKey $config.MyAzureStorageAccountKey `
                               -StorageContainer $config.MyAzureStorageContainer `
                               -Recurse
}

.Parameter Path
The path of files to upload relative to the directory above your powerdelivery project.

.Parameter Destination
The directory in which to place uploaded files.

.Parameter Credential
The Windows Azure account credentials to use.

.Parameter SubscriptionId
A Windows Azure subscription that the account in the Credential parameter is permitted 
to use.

.Parameter StorageAccountName
A Windows Azure storage account that the account in the Credential parameter is permitted 
to access.

.Parameter StorageAccountKey
A Windows Azure storage account key that matches the StorageAccountName parameter providing 
read and write access.

.Parameter StorageContainer
A container within the Windows Azure storage account referred to in the StorageAccountName 
parameter into which to upload files.

.Parameter Filter
A comma-separated list of file extensions to filter for. Others will be excluded.

.Parameter Include
A comma-separated list of paths to include. Others will be excluded.

.Parameter Exclude
A comma-separated list of paths to exclude. Others will be included.

.Parameter Recurse
Uploads files in subdirectories below the directory specified by the Path parameter.

.Parameter Keep
The number of previous releases to keep. Defaults to 5.
#>
function Publish-DeliveryFilesToAzure {
  param(
    [Parameter(Position=0,Mandatory=1)][string] $Path,
    [Parameter(Position=1,Mandatory=1)][string] $Destination,
    [Parameter(Position=2,Mandatory=1)][PSCredential] $Credential,
    [Parameter(Position=3,Mandatory=1)][string] $SubscriptionId,
    [Parameter(Position=4,Mandatory=1)][string] $StorageAccountName,
    [Parameter(Position=5,Mandatory=1)][string] $StorageAccountKey,
    [Parameter(Position=6,Mandatory=1)][string] $StorageContainer,
    [Parameter(Position=7,Mandatory=0)][string] $Filter,
    [Parameter(Position=8,Mandatory=0)][string[]] $Include,
    [Parameter(Position=9,Mandatory=0)][string[]] $Exclude,
    [Parameter(Position=10,Mandatory=0)][switch] $Recurse,
    [Parameter(Position=11,Mandatory=0)][int] $Keep = 5
  )

  $verbose = Test-Verbose

  if (-not ("win32.Shell" -as [type])) {
      Add-Type -Namespace win32 -Name Shell -MemberDefinition @"
      [DllImport("Shlwapi.dll", SetLastError = true, CharSet = CharSet.Auto)]
      public static extern bool PathRelativePathTo(System.Text.StringBuilder lpszDst,
      string From, System.IO.FileAttributes attrFrom, String to, System.IO.FileAttributes attrTo);
"@
  }

  Import-Module Azure

  # Set the active Azure account
  Add-AzureAccount -Credential $Credential | Out-Null

  if ($verbose) {
    Write-Host "Using Azure subscription ""$SubscriptionId"""
  }

  # Set the active subscription
  Select-AzureSubscription -SubscriptionId $SubscriptionId

  if ($verbose) {
    Write-Host "Using Azure storage account ""$StorageAccountName"""
  }

  # Connect to the Azure storage account
  $storageContext = New-AzureStorageContext -StorageAccountName $StorageAccountName `
                                            -StorageAccountKey $StorageAccountKey

  
  # Get the powerdelivery share
  $releasesContainer = Get-AzureStorageContainer -Name $StorageContainer `
                                                 -Context $storageContext `
                                                 -ErrorAction SilentlyContinue
  if (!$releasesContainer) {
    throw "Azure storage container $StorageContainer not found in account $StorageAccountName."
  }

  $appDataDir = [Environment]::GetFolderPath("ApplicationData")
  $tempGuidDir = Join-Path $appDataDir "PowerDelivery\$([System.Guid]::NewGuid())"
  $tempProjectDir = Join-Path $tempGuidDir $target.ProjectName
  $tempReleaseDir = Join-Path $tempProjectDir $target.StartedAt

  New-Item -ItemType Directory $tempReleaseDir | Out-Null

  try {

    # Check if path is directory
    $pathIsDirectory = (Get-Item $Path) -is [System.IO.DirectoryInfo]

    if ($pathIsDirectory) {

      $copyArgs = @{
        Path = $Path;
        Destination = "$tempReleaseDir\$Destination";
        Filter = $Filter;
        Exclude = $Exclude;
        Include = $Include
      }

      if ($Recurse) {
        $copyArgs.Add('Recurse', $Recurse)
      }

      # Copy files to temp dir
      Copy-Item @copyArgs | Out-Null
    }
    else {

      # Copy file to temp dir
      Copy-Item $Path "$tempReleaseDir\$Destination" | Out-Null
    }

    # Upload to azure
    Set-Location $tempGuidDir
    foreach ($file in (Get-ChildItem . -Recurse -File)) {

      $relativePath = New-Object -TypeName System.Text.StringBuilder 260
      [win32.Shell]::PathRelativePathTo($relativePath, $tempProjectDir, [System.IO.FileAttributes]::Normal, $file.FullName, [System.IO.FileAttributes]::Normal) | Out-Null

      Set-AzureStorageBlobContent -File $file.FullName `
                                  -Blob $relativePath.ToString() `
                                  -Container $StorageContainer `
                                  -Context $storageContext | Out-Null
    }

    # Get all release files
    $allReleaseFiles = Get-AzureStorageBlob -Blob "$($target.ProjectName)*" `
                                            -Container $StorageContainer `
                                            -Context $storageContext

    $releases = @()

    # Iterate release files to find releases
    foreach ($releaseFile in $allReleaseFiles) {
      $pathSegments = $releaseFile.Name -split '/'
      $releaseSegment = $pathSegments[1]
      if (!($releases -contains $releaseSegment)) {
        $releases += $releaseSegment
      }
    }

    # If we have releases to delete
    if ($releases.count -gt $Keep) {

      # Determine how many to remove
      $oldReleaseCount = $releases.count - $Keep

      # Get the releases to delete
      $releasesToDelete = $releases | Sort-Object | Select -First $oldReleaseCount

      # Iterate release files
      foreach ($releaseFile in $allReleaseFiles) {
      
        # Iterate releases to delete
        foreach ($releaseToDelete in $releasesToDelete) {

          $releasePrefix = "$($target.ProjectName)/$releaseToDelete"

          # Check whether blob name starts with release prefix
          if ($releaseFile.Name.StartsWith($releasePrefix)) {

            # Delete the blob
            Remove-AzureStorageBlob -Blob $releaseFile.Name `
                                    -Container $StorageContainer `
                                    -Context $storageContext `
                                    -Force | Out-Null
          }
        }
      }
    }
  }
  finally {
    Set-Location $target.StartDir

    # Cleanup
    Remove-Item $tempGuidDir -Recurse -Force
  }
}

Export-ModuleMember -Function Publish-DeliveryFilesToAzure
tools\PowerDelivery\Cmdlets\Publish-DeliveryFilesToS3.ps1
<#
.Synopsis
Uploads files for a powerdelivery release to AWS Simple Storage Service for use by nodes that will host the product.

.Description
Uploads files for a powerdelivery release to AWS Simple Storage Service for use by nodes that will host the product. 
All files that are uploaded are prefixed with a path that contains the name of the powerdelivery project and a 
timestamp of the date and time that the target started.

.Example
Delivery:Role {
  param($target, $config, $node)
  
  # Recursively uploads files within the folder "MyApp\bin\Release" 
  # to an AWS S3 bucket below a <ProjectName>\<StartedAt> path.
  Publish-DeliveryFilesToS3 -Path "MyApp\bin\Debug" `
                            -Destination "MyApp" `
                            -ProfileName "MyProfile" `
                            -BucketName "MyAppReleases" `
                            -Recurse
}

.Parameter Path
The path of files to upload relative to the directory above your powerdelivery project.

.Parameter Destination
The directory in which to place uploaded files.

.Parameter ProfileName
The name of the AWS profile containing credentials to use. 
See https://docs.aws.amazon.com/powershell/latest/userguide/specifying-your-aws-credentials.html

.Parameter BucketName
The name of the S3 bucket to publish the release to.

.Parameter Filter
A comma-separated list of file extensions to filter for. Others will be excluded.

.Parameter Include
A comma-separated list of paths to include. Others will be excluded.

.Parameter Exclude
A comma-separated list of paths to exclude. Others will be included.

.Parameter Recurse
Uploads files in subdirectories below the directory specified by the Path parameter.

.Parameter Keep
The number of previous releases to keep. Defaults to 5.

.Parameter ProfilesLocation
The location to look in for the AWS profile containing credentials.
See https://docs.aws.amazon.com/powershell/latest/userguide/specifying-your-aws-credentials.html
#>
function Publish-DeliveryFilesToS3 {
  param(
    [Parameter(Position=0,Mandatory=1)][string] $Path,
    [Parameter(Position=1,Mandatory=1)][string] $Destination,
    [Parameter(Position=2,Mandatory=1)][string] $ProfileName,
    [Parameter(Position=3,Mandatory=1)][string] $BucketName,
    [Parameter(Position=4,Mandatory=0)][string] $Filter,
    [Parameter(Position=5,Mandatory=0)][string[]] $Include,
    [Parameter(Position=6,Mandatory=0)][string[]] $Exclude,
    [Parameter(Position=7,Mandatory=0)][switch] $Recurse,
    [Parameter(Position=8,Mandatory=0)][int] $Keep = 5,
    [Parameter(Position=9,Mandatory=0)][string] $ProfilesLocation
  )

  $verbose = Test-Verbose

  if (-not ("win32.Shell" -as [type])) {
      Add-Type -Namespace win32 -Name Shell -MemberDefinition @"
      [DllImport("Shlwapi.dll", SetLastError = true, CharSet = CharSet.Auto)]
      public static extern bool PathRelativePathTo(System.Text.StringBuilder lpszDst,
      string From, System.IO.FileAttributes attrFrom, String to, System.IO.FileAttributes attrTo);
"@
  }

  Import-Module AWSPowerShell

  $setAwsCredentialsArgs = @{
    ProfileName = $ProfileName
  }

  if (![String]::IsNullOrEmpty($ProfilesLocation)) {
    $setAwsCredentialsArgs.Add("ProfilesLocation", $ProfilesLocation)
  }

  # Set the active AWS credentials
  Set-AwsCredentials @$setAwsCredentialsArgs

  if ($verbose) {
    Write-Host "Using AWS profile ""$ProfileName"""
  }

  # Connect to the S3 bucket
  $bucket = Get-S3Bucket $BucketName
  if (!$bucket) {
    throw "S3 bucket $BucketName not found."
  }

  $appDataDir = [Environment]::GetFolderPath("ApplicationData")
  $tempGuidDir = Join-Path $appDataDir "PowerDelivery\$([System.Guid]::NewGuid())"
  $tempProjectDir = Join-Path $tempGuidDir $target.ProjectName
  $tempReleaseDir = Join-Path $tempProjectDir $target.StartedAt

  New-Item -ItemType Directory $tempReleaseDir | Out-Null

  try {

    # Check if path is directory
    $pathIsDirectory = (Get-Item $Path) -is [System.IO.DirectoryInfo]

    if ($pathIsDirectory) {

      $copyArgs = @{
        Path = $Path;
        Destination = "$tempReleaseDir\$Destination";
        Filter = $Filter;
        Exclude = $Exclude;
        Include = $Include
      }

      if ($Recurse) {
        $copyArgs.Add('Recurse', $Recurse)
      }

      # Copy files to temp dir
      Copy-Item @copyArgs | Out-Null
    }
    else {

      # Copy file to temp dir
      Copy-Item $Path "$tempReleaseDir\$Destination" | Out-Null
    }

    # Upload to S3
    Set-Location $tempGuidDir
    foreach ($file in (Get-ChildItem . -Recurse -File)) {

      $relativePath = New-Object -TypeName System.Text.StringBuilder 260
      [win32.Shell]::PathRelativePathTo($relativePath, $tempProjectDir, [System.IO.FileAttributes]::Normal, $file.FullName, [System.IO.FileAttributes]::Normal) | Out-Null

      Write-S3Object -BucketName $BucketName `
                     -Key $relativePath.ToString() `
                     -File $file.FullName | Out-Null
    }

    # Get all release files
    $allReleaseFiles = Get-S3Object -BucketName $BucketName `
                                    -KeyPrefix $target.ProjectName

    $releases = @()

    # Iterate release files to find releases
    foreach ($releaseFile in $allReleaseFiles) {
      $pathSegments = $releaseFile.Key -split '/'
      $releaseSegment = $pathSegments[1]
      if (!($releases -contains $releaseSegment)) {
        $releases += $releaseSegment
      }
    }

    # If we have releases to delete
    if ($releases.count -gt $Keep) {

      # Determine how many to remove
      $oldReleaseCount = $releases.count - $Keep

      # Get the releases to delete
      $releasesToDelete = $releases | Sort-Object | Select -First $oldReleaseCount

      # Iterate release files
      foreach ($releaseFile in $allReleaseFiles) {
      
        # Iterate releases to delete
        foreach ($releaseToDelete in $releasesToDelete) {

          $releasePrefix = "$($target.ProjectName)/$releaseToDelete"

          # Check whether s3 object key starts with release prefix
          if ($releaseFile.Key.StartsWith($releasePrefix)) {

            # Delete the S3 object
            Remove-S3Object -BucketName $BucketName `
                            -Key $releaseFile.Key `
                            -Force | Out-Null
          }
        }
      }
    }
  }
  finally {
    Set-Location $target.StartDir

    # Cleanup
    Remove-Item $tempGuidDir -Recurse -Force
  }
}

Export-ModuleMember -Function Publish-DeliveryFilesToS3
tools\PowerDelivery\Cmdlets\Start-Delivery.ps1
<#
.Synopsis
Starts deployment or rollback of a target with powerdelivery.

.Description
Starts deployment or rollback of a target with powerdelivery. Must be run in the parent directory of your powerdelivery project.

.Example
Start-Delivery MyApp Release Production

.Parameter ProjectName
The name of the project. Powerdelivery looks for a subdirectory with this name suffixed with "Delivery".

.Parameter TargetName
The name of the target to run. Must match the name of a file in the Targets subdirectory of your powerdelivery project without the file extension.

.Parameter EnvironmentName
The name of the environment to target during the run. Must match the name of a file in the Environments subdirectory of your powerdelivery project without the file extension.

.Parameter Properties
A hash of properties to pass to the target. Typically used to pass information from build servers.

.Parameter Rollback
Switch that when set causes the Down block of roles to be called instead of Up, performing a rollback.
#>
function Start-Delivery {
  [CmdletBinding()]
  param (
    [Parameter(Position=0,Mandatory=1)][string] $ProjectName,
    [Parameter(Position=1,Mandatory=1)][string] $TargetName,
    [Parameter(Position=2,Mandatory=1)][string] $EnvironmentName,
    [Parameter(Position=3,Mandatory=0)][hashtable] $Properties = @{},
    [Parameter(Position=4,Mandatory=0)][switch] $Rollback
  )

  $ErrorActionPreference = 'Stop'

  winrm quickconfig -Force | Out-Null
  Enable-PSRemoting -Force -SkipNetworkProfileCheck | Out-Null

  # Verify running as Administrator
  $user = [Security.Principal.WindowsIdentity]::GetCurrent();
  if (!(New-Object Security.Principal.WindowsPrincipal $user).IsInRole([Security.Principal.WindowsBuiltinRole]::Administrator)) {
    throw "Please run PowerDelivery using an elevated (Administrative) command prompt."
  }

  $pow.colors = @{
    SuccessForeground = 'Green'; 
    FailureForeground = 'Red'; 
    StepForeground = 'Magenta'; 
    RoleForeground = 'Yellow';
    CommandForeground = 'White'; 
    LogFileForeground = 'White' 
  }

  $pow.target = @{
    ProjectName = $ProjectName;
    TargetName = $TargetName;
    EnvironmentName = $EnvironmentName;
    Revision = $Revision;
    RequestedBy = (whoami).ToUpper();
    StartDate = Get-Date;
    StartDir = Get-Location;
    StartedAt = Get-Date -Format "yyyyMMdd_HHmmss";
    Properties = $Properties;
    Credentials = New-Object "System.Collections.Generic.Dictionary[String, System.Management.Automation.PSCredential]";
    Secrets = @{}
  }

  $pow.buildFailed = $false
  $pow.inBuild = $true
  $pow.roles = @{}

  # Get the running version of powerdelivery
  if (Get-Module powerdelivery)
  {
      $pow.version = Get-Module powerdelivery | select version | ForEach-Object { $_.Version.ToString() }
  }
  else
  {
      $pow.version = "SOURCE"
  }

  Write-Host
  Write-Host "PowerDelivery v$($pow.version)" -ForegroundColor $pow.colors['SuccessForeground']
  Write-Host "Target ""$TargetName"" started by ""$($pow.target.RequestedBy)"""
  
  function LoadRoleScript($role) {

    # Make sure the role script exists
    if (!($pow.roles.ContainsKey($role))) {
      $rolePath = "$($ProjectName)Delivery\Roles\$role\Always.ps1"
      $roleScript = (Join-Path $pow.target.StartDir $rolePath)
      if (!(Test-Path $roleScript)) {
        Write-Host "Role script $rolePath could not be found." -ForegroundColor Red
        throw 
      }#

      # Run the role script to get the script block
      Invoke-Expression -Command ".\$rolePath"
    }
  }

  # Writes the starting status message for a role
  #
  function WriteRoleStart($role, $hostOrConnectionURI) {

    Write-Host "[--------- $role -> ($hostOrConnectionURI)" -ForegroundColor $pow.colors['RoleForeground']
  }

  # Invokes a role on a host
  #
  function InvokeRoleOnHost($nodes, $role, $hostName) {

    LoadRoleScript -role $role
    WriteRoleStart -role $role -hostOrConnectionURI $hostName

    InvokeRole -nodes $nodes -role $role -hostName $hostName
  }

  # Invokes a role on a connection
  function InvokeRoleOnConnection($nodes, $role, $connectionURI) {

    LoadRoleScript -role $role
    WriteRoleStart -role $role -hostOrConnectionURI $connectionURI

    InvokeRole -nodes $nodes -role $role -connectionURI $connectionURI
  }

  # Invokes a role
  #
  function InvokeRole($nodes, $role, $hostName, $connectionURI) {

    $hostOrConnectionURI = $hostName

    if ([String]::IsNullOrWhiteSpace($hostName)) {
      $hostOrConnectionURI = $connectionURI
    }

    # Determine whether to roll up or down
    $blockToRun = $pow.roles.Item($role)[0];
    if ($Rollback) {
      $blockToRun = $pow.roles.Item($role)[1];
    }

    # Must have a rollback or up block to run
    if ($blockToRun) {

      $commandArgs = @{
        ScriptBlock = $blockToRun;
        ArgumentList = @($pow.target, $config, $hostOrConnectionURI)
      }

      # Check whether a remote node
      if ([String]::IsNullOrWhiteSpace($hostName) -or ($hostName.ToLower() -ne 'localhost')) {

        # Set the computer name or connection URI
        if ([String]::IsNullOrWhiteSpace($connectionURI)) {
          $commandArgs.Add('ComputerName', $nodeName)
        }
        else {
          $commandArgs.Add('ConnectionURI', $connectionURI) 

          if ($nodes.ContainsKey('UseSSL')) {
            throw "Role $role cannot set UseSSL and Connection together."
          }
        }

        $commandArgs.Add('EnableNetworkAccess', 1)

        # Lookup remote credentials if specified
        if ($nodes.ContainsKey('Credential')) {
          $credentialName = $nodes.Credential
          if (!$pow.target.Credentials.ContainsKey($credentialName)) {
            throw "Role $role requires credential $credentialName which were not loaded. Are you missing the key file?"
          }
          else {
            $commandArgs.Add('Credential', $pow.target.Credentials.Item($credentialName))
          }
        }

        # Add UseSSL if specified
        if ($nodes.ContainsKey('UseSSL')) {
          $commandArgs.Add('UseSSL', 1);
        }

        # Add authentication options if using credentials
        if ($commandArgs.ContainsKey('Credential')) {

          $authentication = 'Default'

          # Update authentication of the command if specified on the nodes
          if ($nodes.ContainsKey('Authentication')) {
            $authentication = $nodes.Authentication
          } 

          # Set authentication of the command
          $commandArgs.Add('Authentication', $authentication)

          # Setup CredSSP if specified
          if ($authentication.ToLower() -eq 'credssp') {

            $trustedHost = $hostName

            # Verify that a host was specified
            if ([String]::IsNullOrWhiteSpace($hostName)) {
              $uri = New-Object System.Uri -ArgumentList $connectionURI
              $trustedHost = $uri.Host
            }
         
            $credSSP = Get-WSManCredSSP
            $nodeExists = $false

            # Check whether remote node exists in trusted hosts
            if ($credSSP -ne $null) {
              if ($credSSP.length -gt 0) {
                $trustedClients = $credSSP[0].Substring($credSSP[0].IndexOf(":") + 2)
                $trustedClientsList = $trustedClients -split "," | % { $_.Trim() }
                if ($trustedClientsList.Contains("wsman/$($trustedHost.ToLower())")) {
                  $nodeExists = $true
                }
              }
            }

            # Enable CredSSP to remote node if not found in trusted hosts
            if (!$nodeExists) {
              Enable-WSManCredSSP -Role Client -DelegateComputer $trustedHost.ToLower() -Force | Out-Null
            }
          }
        }
      }

      # Run the role
      try {
        Invoke-Command @commandArgs
      }
      catch {
        throw "Error in role ""$role"" on $hostOrConnectionURI" + [Environment]::NewLine, $_
      }

      Set-Location $pow.target.StartDir
    }
  }

  try {
    if ($Rollback) {
      Write-Host "Rolling back ""$ProjectName"" in ""$EnvironmentName"" environment..."
    }
    else {
      Write-Host "Delivering ""$ProjectName"" to ""$EnvironmentName"" environment..."
    }
    Write-Host

    $myDocumentsFolder = [Environment]::GetFolderPath("MyDocuments")

    # Test for secrets
    $secretsPath = "$($ProjectName)Delivery\Secrets"
    if (Test-Path $secretsPath) {

      # Iterate secret key directories
      foreach ($keyDirectory in (Get-ChildItem -Directory $secretsPath)) {

        # Try to get the key
        $keyBytes = GetKeyBytes -ProjectDir "$($ProjectName)Delivery" -KeyName $keyDirectory

        if ($keyBytes -ne $null) {

          # Iterate secrets
          foreach ($secretFile in (Get-ChildItem -File -Filter *.secret $keyDirectory.FullName)) { 

            $secretName = [IO.Path]::GetFileNameWithoutExtension($secretFile)
            $secretFullPath = Join-Path $keyDirectory $secretFile

            # Try to decrypt the secret
            $secret = $null
            try {
              $secret = Get-Content $secretFullPath | ConvertTo-SecureString -Key $keyBytes
            }
            catch {
              throw "Couldn't decrypt $secretFullPath with key $keyDirectory - $_"
            }

            # Add secret to hash in target
            $pow.target.Secrets.Add($secretName, $secret)
          }

          # Check whether credentials exist
          $credsPath = Join-Path $keyDirectory.FullName "Credentials"
          if (Test-Path $credsPath) {

            # Iterate credentials
            foreach ($credentialsFile in (Get-ChildItem -File -Filter *.credential $credsPath)) {

              $credsFullPath = Join-Path $credsPath $credentialsFile

              # Try to decrypt the password
              $password = $null
              try {
                $password = Get-Content $credsFullPath | ConvertTo-SecureString -Key $keyBytes
              }
              catch {
                throw "Couldn't decrypt $credsFullPath with key $keyDirectory - $_"
              }

              # Fix up the username
              $credsFileUserName = $credentialsFile -replace '#', '\\'
              $userName = [IO.Path]::GetFileNameWithoutExtension($credsFileUserName)

              # Create the PowerShell credential
              $userCredential = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $userName, $password

              # Add credentials to hash in target
              $pow.target.Credentials.Add($userName.ToLower(), [PSCredential]$userCredential)
            }
          }
        }
      }
    }

    # Test for shared configuration
    $sharedConfigPath = "$($ProjectName)Delivery\Configuration\_Shared.ps1"
    $sharedConfigScript = (Join-Path $pow.target.StartDir $sharedConfigPath)
    if (!(Test-Path $sharedConfigScript)) {
      Write-Host "Shared configuration script $sharedConfigPath could not be found." -ForegroundColor Red
      throw
    }

    # Load shared configuration
    try {
      $pow.sharedConfig = Invoke-Command -ComputerName localhost -File $sharedConfigScript -ArgumentList $pow.target
    }
    catch {
      Write-Host "Error occurred loading $sharedConfigPath." -ForegroundColor Red
      throw
    }

    # Test for environment configuration
    $envConfigPath = "$($ProjectName)Delivery\Configuration\$EnvironmentName.ps1"
    $envConfigScript = (Join-Path $pow.target.StartDir $envConfigPath)
    if (!(Test-Path $envConfigScript)) {
      Write-Host "Environment configuration script $envConfigPath could not be found." -ForegroundColor Red
      throw 
    }

    # Load environment configuration
    try {
      $pow.envConfig = Invoke-Command -ComputerName localhost -File $envConfigScript -ArgumentList @($pow.target, $pow.sharedConfig)
    }
    catch {
      Write-Host "Error occurred loading $envConfigPath." -ForegroundColor Red
      throw
    }

    $config = @{}

    # Add environment-specific config settings
    foreach ($envConfigSetting in $pow.envConfig.GetEnumerator()) {
      $config.Add($envConfigSetting.Key, $envConfigSetting.Value)
    }

    # Add shared config settings
    foreach ($sharedConfigSetting in $pow.sharedConfig.GetEnumerator()) {
      if (!($config.ContainsKey($sharedConfigSetting.Key))) {
        $config.Add($sharedConfigSetting.Key, $sharedConfigSetting.Value)
      }
    }

    # Test for environment
    $envPath = "$($ProjectName)Delivery\Environments\$EnvironmentName.ps1"
    $envScript = (Join-Path $pow.target.StartDir $envPath)
    if (!(Test-Path $envScript)) {
      Write-Host "Environment script $envPath could not be found." -ForegroundColor Red
      throw
    }

    # Load environment
    try {
      $pow.target.Environment = Invoke-Command -ComputerName localhost -File $envScript -ArgumentList @($pow.target, $config)
    }
    catch {
      Write-Host "Error occurred loading $envPath." -ForegroundColor Red
      throw
    }

    # Test for target
    $targetPath = "$($ProjectName)Delivery\Targets\$TargetName.ps1"
    $targetScript = (Join-Path $pow.target.StartDir $targetPath)
    if (!(Test-Path $targetScript)) {
      Write-Host "Target script $targetPath could not be found." -ForegroundColor Red
      throw
    }

    # Load target
    try {
      $pow.targetScript = Invoke-Expression -Command $targetScript
    }
    catch {
      Write-Host "Error occurred loading $targetPath." -ForegroundColor Red
      throw
    }

    # Iterate steps of the target
    foreach ($targetStep in $pow.targetScript.GetEnumerator()) {
      Write-Host "[----- $($targetStep.Key)" -ForegroundColor $pow.colors['StepForeground']

      # Iterate sets of nodes in the step
      foreach ($node in $targetStep.Value.Nodes) {

        # Make sure the environment contains the nodes
        if (!$pow.target.Environment.ContainsKey($node)) {
          Write-Host "Step $($targetStep.Key) of target $TargetName refers to nodeset $node not found in $EnvironmentName environment." -ForegroundColor Red
          throw
        }

        # Get the current set of nodes for the target
        $nodes = $pow.target.Environment.Item($node)

        # Make sure they didn't specify hosts and connections together
        if ($nodes.ContainsKey('Hosts') -and $nodes.ContainsKey('Connections')) {
          throw "Nodes $node cannot combine Hosts and Connections."
        }

        # Iterate hosts in the set
        if ($nodes.ContainsKey('Hosts')) {
          foreach ($hostName in $nodes.Hosts) {
            # Iterate roles
            foreach ($role in $targetStep.Value.Roles) {
              InvokeRoleOnHost -nodes $nodes -role $role -hostName $hostName
            }
          }
        }
        # Iterate connections in the set
        elseif ($nodes.ContainsKey('Connections')) {
          # Iterate connections in the set
          foreach ($connectionURI in $nodes.Connections) {
            # Iterate roles
            foreach ($role in $targetStep.Value.Roles) {
              InvokeRoleOnConnection -nodes $nodes -role $role -connectionURI $connectionURI
            }
          }
        }
      }
    }
  }
  catch {
    $pow.buildFailed = $true
    throw
  }
  finally {
    $build_time = New-Timespan -Start ($pow.target.StartDate) -End (Get-Date)
    $build_time_string = ''

    $build_time_days = $build_time.Days
    if ($build_time_days -gt 0) {
      $build_time_string += "$build_time_days days"
    }

    $build_time_hours = $build_time.Hours
    if ($build_time_hours -gt 0) {
      if ($build_time_string.Length -gt 0) {
        $build_time_string += ' '
      }
      $build_time_string += "$build_time_hours hrs"
    }

    $build_time_minutes = $build_time.Minutes
    if ($build_time_minutes -gt 0) {
      if ($build_time_string.Length -gt 0) {
        $build_time_string += ' '
      }
      $build_time_string += "$build_time_minutes min"
    }

    $build_time_seconds = $build_time.Seconds
    if ($build_time_seconds -gt 0) {
      if ($build_time_string.Length -gt 0) {
        $build_time_string += ' '
      }
      $build_time_string += "$build_time_seconds sec"
    }

    $build_time_ms = $build_time.Milliseconds
    if ($build_time_ms -gt 0) {
      if ($build_time_string.Length -gt 0) {
        $build_time_string += ' '
      }
      $build_time_string += "$build_time_ms ms"
    }

    Write-Host

    if ($pow.buildFailed) {
      Write-Host "Target ""$TargetName"" failed in $build_time_string." -ForegroundColor $pow.colors['FailureForeground']
    }
    else {
      Write-Host "Target ""$TargetName"" succeeded in $build_time_string." -ForegroundColor $pow.colors['SuccessForeground']
    }

    Set-Location $pow.target.StartDir | Out-Null
  }
}

Export-ModuleMember -Function Start-Delivery
tools\PowerDelivery\Cmdlets\Write-RelativePath.ps1
<#
.Synopsis
Returns an absolute path relative to the current directory.

.Description
Returns an absolute path relative to the current directory.

.Example
Write-RelativePath "C:\SomeDir\SomeOtherDir"

.Parameter Path
The absolute path to return the relative form of.
#>
function Write-RelativePath {
  [CmdletBinding()]
  param (
    [Parameter(Position=0,Mandatory=0)][string] $path
  )

  $pathUri = New-Object -TypeName System.Uri -ArgumentList $path

  if ($pathUri.IsUnc) {
    $path
  }
  else {
    if (-not ("win32.Shell" -as [type])) {
      Add-Type -Namespace win32 -Name Shell -MemberDefinition @"
      [DllImport("Shlwapi.dll", SetLastError = true, CharSet = CharSet.Auto)]
      public static extern bool PathRelativePathTo(System.Text.StringBuilder lpszDst,
      string From, System.IO.FileAttributes attrFrom, String to, System.IO.FileAttributes attrTo);
"@
    }

    $fullPath = [System.IO.Path]::GetFullPath($path)

    $pathBldr = New-Object -TypeName System.Text.StringBuilder 260

    $startDir = Get-Location

    if ($powerdelivery.inBuild) {
      $startDir = $pow.target.StartDir
    }
    
    $result = [win32.Shell]::PathRelativePathTo($pathBldr, $startDir, [System.IO.FileAttributes]::Normal, $fullPath, [System.IO.FileAttributes]::Normal)
    if ($result) {
      $pathBldr.ToString()
    }
    else {
      "NOTFOUND"
    }
  }
}

Export-ModuleMember -Function Write-RelativePath
tools\PowerDelivery\PowerDelivery.psd1
 
tools\PowerDelivery\PowerDelivery.psm1
<# PowerDelivery.psm1

Script for PowerShell module.

http://www.powerdelivery.io
#>

function GetProjectDirectory {
  if (!((Test-Path 'Targets') -and (Test-Path 'Environments') -and (Test-Path 'Roles'))) {
    throw "This command must be run from within a powerdelivery project directory."
  }
  Get-Location
}

function ValidateNewFileName($Type, $FileName) {
  $isValidName = "^[a-zA-Z0-9]+$"
  if (!($FileName -match $isValidName)) {
    throw "Please use a $Type that only includes alphanumeric characters and no spaces."
  }
}

function GetMyDocumentsFolder {
  [Environment]::GetFolderPath("MyDocuments")
}

function GetKeyBytes($ProjectDir, $KeyName, [switch]$ThrowOnError) {
  $myDocumentsFolder = GetMyDocumentsFolder
  $keysFolderPath = Join-Path $myDocumentsFolder "PowerDelivery\Keys\$ProjectDir"
  $keyFilePath = Join-Path $keysFolderPath "$KeyName.key"

  if (!(Test-Path $keyFilePath)) {
    if ($ThrowOnError) {
      throw "Key not found at $keyFilePath."
    }
    else {
      return $null
    }
  }
  $keyString = Get-Content $keyFilePath
  try {
    [Convert]::FromBase64String($keyString)
  }
  catch {
    throw "Key $KeyName is invalid - $_"
  }
}

function GetNewKey {
  $key = New-Object Byte[] 32
  [Security.Cryptography.RNGCryptoServiceProvider]::Create().GetBytes($key)
  [Convert]::ToBase64String($key)
}

# Load cmdlets
$cmdletsDir = (Join-Path $PSScriptRoot "Cmdlets")
gci $cmdletsDir -Filter "*.ps1" | ForEach-Object { . (Join-Path $cmdletsDir $_.Name) }

$env:TERM = "msys"

$script:pow = @{}
$pow.scriptDir = Split-Path $MyInvocation.MyCommand.Path
tools\PowerDelivery\Templates\Configuration.ps1.template
<# See http://www.powerdelivery.io/variables.html #>
param($target, $shared)
@{
  # Define hash values with environment-specific variables here
}
tools\PowerDelivery\Templates\Environment.ps1.template
<# See http://www.powerdelivery.io/environments.html #>
param($target, $config)
@{
  # Define sets of nodes here
}
tools\PowerDelivery\Templates\Role.ps1.template
<# See http://www.powerdelivery.io/roles.html #>
Delivery:Role -Up {
  param($target, $config, $node)

  # Write PowerShell deployment logic here
} -Down {
  param($target, $config, $node)

  # Write PowerShell rollback logic here (if necessary)
}
tools\PowerDelivery\Templates\Target.ps1.template
<# See http://www.powerdelivery.io/targets.html #>
[ordered]@{
  # Define the steps in your target here
}
tools\PowerDelivery\Templates\_Shared.ps1.template
<# See http://www.powerdelivery.io/variables.html #>
param($target)
@{
  # Define hash values with shared variables here
}

Log in or click on link to see number of positives.

In cases where actual malware is found, the packages are subject to removal. Software sometimes has false positives. Moderators do not necessarily validate the safety of the underlying software, only that a package retrieves software from the official distribution point and/or validate embedded software against official distribution point (where distribution rights allow redistribution).

Chocolatey Pro provides runtime protection from possible malware.

Add to Builder Version Downloads Last Updated Status
PowerDelivery 3 3.0.0 329 Saturday, June 18, 2016 Approved

Discussion for the PowerDelivery 3 Package

Ground Rules:

  • This discussion is only about PowerDelivery 3 and the PowerDelivery 3 package. If you have feedback for Chocolatey, please contact the Google Group.
  • This discussion will carry over multiple versions. If you have a comment about a particular version, please note that in your comments.
  • The maintainers of this Chocolatey Package will be notified about new comments that are posted to this Disqus thread, however, it is NOT a guarantee that you will get a response. If you do not hear back from the maintainers after posting a message below, please follow up by using the link on the left side of this page or follow this link to contact maintainers. If you still hear nothing back, please follow the package triage process.
  • Tell us what you love about the package or PowerDelivery 3, or tell us what needs improvement.
  • Share your experiences with the package, or extra configuration or gotchas that you've found.
  • If you use a url, the comment will be flagged for moderation until you've been whitelisted. Disqus moderated comments are approved on a weekly schedule if not sooner. It could take between 1-5 days for your comment to show up.
comments powered by Disqus