Last active
July 22, 2021 02:45
-
-
Save steviecoaster/2cc038d0822b9979e856c5af38125a51 to your computer and use it in GitHub Desktop.
Backup Chocolatey Packages To File
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<# | |
.SYNOPSIS | |
Creates a packages.config file from installed choco packages | |
.PARAMETER SourceFriendlyName | |
The friendly name of an available choco source on the system. This will explicity set the source in the config file | |
such that installation on the new system will come from this source. | |
.PARAMETER OutputFile | |
The config file to save output too. Must end in '.config'. | |
.EXAMPLE | |
./New-PackageConfig.ps1 -SourceFriendlyName chocolatey -OutputFile 'C:\temp\packages.config' | |
#> | |
[cmdletBinding()] | |
param( | |
[parameter(Mandatory = $true)] | |
[string] | |
$SourceFriendlyName, | |
[parameter(Mandatory = $true)] | |
[String] | |
$OutputFile | |
) | |
begin { | |
if ([System.IO.Path]::GetExtension($OutputFile) -ne '.config') { | |
throw "Must specify a file ending in '.config'" | |
} | |
else { | |
if (-not (Test-Path $OutputFile)) { | |
$null = New-Item $OutputFile -ItemType File -Force | |
} | |
} | |
} | |
process { | |
$string = @' | |
<?xml version="1.0" encoding="utf-8"?> | |
<packages> | |
</packages> | |
'@ | |
$string | Set-Content $OutputFile | |
$xmlDoc = New-Object System.Xml.XmlDocument | |
$xmlDoc.Load("$OutputFile") | |
$sources = choco source list -r | ConvertFrom-Csv -Delimiter '|' -Header "FriendlyName", "SourceUrl", "Enabled", "Username", "Proxy", "Priority", "SelfService", "AdminOnly" | |
$packages = choco list -lo -r | ConvertFrom-Csv -Delimiter '|' -Header 'Packagename', 'PackageVersion' | |
Foreach ($package in $packages) { | |
$script = { | |
$element = $xmlDoc.CreateElement("package") | |
$name = $xmlDoc.CreateAttribute("id") | |
$name.Value = "$($package.Packagename)" | |
$version = $xmlDoc.CreateAttribute("version") | |
$version.Value = "$($package.PackageVersion)" | |
$source = $xmlDoc.CreateAttribute("source") | |
$source.Value = "$(($sources | ? { $_.FriendlyName -eq "$SourceFriendlyName"}).SourceUrl)" | |
$element.Attributes.Append($name) | |
$element.Attributes.Append($version) | |
$element.Attributes.Append($source) | |
$xmlDoc.LastChild.AppendChild($element) | |
} | |
$sb = [Scriptblock]::Create($script) | |
$null = $sb.InvokeReturnAsIs() | |
$xmlDoc.Save("$OutputFile") | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment