From 4401b11cadb48086c10621a3a87fac9696ba5681 Mon Sep 17 00:00:00 2001 From: TheCakeIsNaOH Date: Sat, 5 Nov 2022 00:22:10 -0500 Subject: [PATCH] (maint) Formatting --- GenerateDocs.ps1 | 573 ++++---- Invoke-Tests.ps1 | 3 +- ScriptFormat.Tests.ps1 | 24 +- build.ps1 | 78 +- docker/Install-ChocolateyInContainer.ps1 | 178 +-- formatting-settings.psd1 | 71 + .../chocolatey/tools/chocolateyInstall.ps1 | 11 +- .../chocolatey/tools/chocolateysetup.psm1 | 1295 +++++++++-------- nuspec/chocolatey/chocolatey/tools/init.ps1 | 6 +- setup.ps1 | 4 +- .../helpers/ChocolateyTabExpansion.ps1 | 270 ++-- .../helpers/chocolateyProfile.psm1 | 12 +- .../helpers/chocolateyScriptRunner.ps1 | 38 +- .../helpers/functions/Format-FileSize.ps1 | 24 +- .../helpers/functions/Get-CheckSumValid.ps1 | 171 +-- .../helpers/functions/Get-ChocolateyPath.ps1 | 16 +- .../helpers/functions/Get-ChocolateyUnzip.ps1 | 346 +++-- .../functions/Get-ChocolateyWebFile.ps1 | 380 ++--- .../functions/Get-EnvironmentVariable.ps1 | 95 +- .../Get-EnvironmentVariableNames.ps1 | 26 +- .../helpers/functions/Get-FtpFile.ps1 | 291 ++-- .../functions/Get-OSArchitectureWidth.ps1 | 61 +- .../functions/Get-PackageParameters.ps1 | 82 +- .../helpers/functions/Get-ToolsLocation.ps1 | 81 +- .../helpers/functions/Get-UACEnabled.ps1 | 43 +- .../functions/Get-UninstallRegistryKey.ps1 | 108 +- .../helpers/functions/Get-VirusCheckValid.ps1 | 14 +- .../helpers/functions/Get-WebFile.ps1 | 480 +++--- .../helpers/functions/Get-WebFileName.ps1 | 354 ++--- .../helpers/functions/Get-WebHeaders.ps1 | 227 +-- .../helpers/functions/Install-BinFile.ps1 | 175 +-- .../Install-ChocolateyEnvironmentVariable.ps1 | 64 +- .../Install-ChocolateyExplorerMenuItem.ps1 | 52 +- .../Install-ChocolateyFileAssociation.ps1 | 42 +- .../Install-ChocolateyInstallPackage.ps1 | 296 ++-- .../functions/Install-ChocolateyPackage.ps1 | 152 +- .../functions/Install-ChocolateyPath.ps1 | 100 +- .../Install-ChocolateyPinnedTaskBarItem.ps1 | 63 +- .../Install-ChocolateyPowershellCommand.ps1 | 69 +- .../functions/Install-ChocolateyShortcut.ps1 | 202 +-- .../Install-ChocolateyVsixPackage.ps1 | 68 +- .../Install-ChocolateyZipPackage.ps1 | 86 +- .../helpers/functions/Install-Vsix.ps1 | 34 +- .../functions/Set-EnvironmentVariable.ps1 | 121 +- .../functions/Set-PowerShellExitCode.ps1 | 33 +- .../Start-ChocolateyProcessAsAdmin.ps1 | 457 +++--- .../functions/Test-ProcessAdminRights.ps1 | 14 +- .../UnInstall-ChocolateyZipPackage.ps1 | 52 +- .../helpers/functions/Uninstall-BinFile.ps1 | 86 +- ...ninstall-ChocolateyEnvironmentVariable.ps1 | 42 +- .../functions/Uninstall-ChocolateyPackage.ps1 | 96 +- .../functions/Update-SessionEnvironment.ps1 | 101 +- .../Write-FunctionCallLogMessage.ps1 | 34 +- .../1.0/tools/chocolateyInstall.ps1 | 4 +- .../1.0.0/tools/chocolateyinstall.ps1 | 4 +- tests/chocolatey-tests/chocolatey.Tests.ps1 | 8 +- .../commands/choco-apikey.Tests.ps1 | 1 - .../commands/choco-config.Tests.ps1 | 7 +- .../commands/choco-deprecated.Tests.ps1 | 2 +- .../commands/choco-export.Tests.ps1 | 28 +- .../commands/choco-feature.Tests.ps1 | 6 +- .../commands/choco-help.Tests.ps1 | 4 +- .../commands/choco-new.Tests.ps1 | 2 +- .../commands/choco-outdated.Tests.ps1 | 2 +- .../commands/choco-push.Tests.ps1 | 12 +- .../commands/choco-removed.Tests.ps1 | 4 +- .../commands/choco-template.Tests.ps1 | 15 +- .../commands/choco-uninstall.Tests.ps1 | 4 +- .../commands/choco-version.Tests.ps1 | 2 +- .../1.0.0/tools/chocolateyinstall.ps1 | 4 +- .../tools/chocolateyinstall.ps1 | 12 +- .../features/PythonSource.Tests.ps1 | 2 +- .../Chocolatey/Get-ChocolateyFeature.ps1 | 7 +- .../common/Chocolatey/Invoke-Choco.ps1 | 9 +- .../Chocolatey/Set-ChocolateyFeature.ps1 | 4 +- ...est-ChocolateyVersionEqualOrHigherThan.ps1 | 2 +- tests/helpers/common/Get-TempDirectory.ps1 | 6 +- .../common/Logging/Get-ChocoLogData.ps1 | 2 +- .../tools/chocolateyinstall.ps1 | 34 +- .../tools/chocolateyuninstall.ps1 | 34 +- .../0.0.1/tools/chocolateyinstall.ps1 | 11 +- .../tools/chocolateyinstall.ps1 | 69 +- .../0.0.1/tools/chocolateyinstall.ps1 | 18 +- .../0.0.2/tools/chocolateyinstall.ps1 | 12 +- .../1.0.0/tools/chocolateyinstall.ps1 | 74 +- .../tools/chocolateybeforemodify.ps1 | 2 +- .../templates/tools/chocolateyinstall.ps1 | 30 +- .../templates/tools/chocolateyuninstall.ps1 | 52 +- .../tools/chocolateybeforemodify.ps1 | 4 +- .../tools/chocolateyinstall.ps1 | 4 +- .../tools/chocolateyuninstall.ps1 | 4 +- .../tools/chocolateybeforemodify.ps1 | 2 +- .../templates/tools/chocolateyinstall.ps1 | 26 +- 93 files changed, 4408 insertions(+), 3922 deletions(-) create mode 100644 formatting-settings.psd1 diff --git a/GenerateDocs.ps1 b/GenerateDocs.ps1 index df55e2d168..5c23b13fb8 100644 --- a/GenerateDocs.ps1 +++ b/GenerateDocs.ps1 @@ -19,7 +19,7 @@ $ErrorActionPreference = 'Stop' -$thisDirectory = (Split-Path -parent $MyInvocation.MyCommand.Definition); +$thisDirectory = (Split-Path -Parent $MyInvocation.MyCommand.Definition); $psModuleName = 'chocolateyInstaller' $psModuleLocation = [System.IO.Path]::GetFullPath("$thisDirectory\src\chocolatey.resources\helpers\chocolateyInstaller.psm1") $docsFolder = [System.IO.Path]::GetFullPath("$thisDirectory\docs\generated") @@ -96,20 +96,20 @@ These are the functions from above as one list. '@ -function Get-Aliases($commandName){ +function Get-Aliases($commandName) { - $aliasOutput = '' - Get-Alias -Definition $commandName -ErrorAction SilentlyContinue | ForEach-Object { $aliasOutput += "``$($_.Name)``$lineFeed"} + $aliasOutput = '' + Get-Alias -Definition $commandName -ErrorAction SilentlyContinue | ForEach-Object { $aliasOutput += "``$($_.Name)``$lineFeed" } - if ($aliasOutput -eq $null -or $aliasOutput -eq '') { - $aliasOutput = 'None' - } + if ($aliasOutput -eq $null -or $aliasOutput -eq '') { + $aliasOutput = 'None' + } - Write-Output $aliasOutput + Write-Output $aliasOutput } function Convert-Example($objItem) { - @" + @" **$($objItem.title.Replace('-','').Trim())** ~~~powershell @@ -120,69 +120,85 @@ $($objItem.remarks | Where-Object { $_.Text } | ForEach-Object { $_.Text.Replace } function Replace-CommonItems($text) { - if ($text -eq $null) {return $text} + if ($text -eq $null) { + return $text + } - $text = $text.Replace("`n",$lineFeed) - $text = $text -replace "\*\*NOTE:\*\*", '> :choco-info: **NOTE** + $text = $text.Replace("`n", $lineFeed) + $text = $text -replace "\*\*NOTE:\*\*", '> :choco-info: **NOTE** > >' - $text = $text -replace '(community feed[s]?[^\]]|community repository)', '[$1](https://community.chocolatey.org/packages)' - $text = $text -replace '(Chocolatey for Business|Chocolatey Professional|Chocolatey Pro)(?=[^\w])', '[$1](https://chocolatey.org/compare)' - $text = $text -replace '(Pro[fessional]\s?/\s?Business)', '[$1](https://chocolatey.org/compare)' - $text = $text -replace '([Ll]icensed editions)', '[$1](https://chocolatey.org/compare)' - $text = $text -replace '([Ll]icensed versions)', '[$1](https://chocolatey.org/compare)' - $text = $text -replace '\(https://docs.chocolatey.org/en-us/create/automatic-packages\)', '(xref:automatic-packaging)' - $text = $text -replace 'Learn more about using this at https://docs.chocolatey.org/en-us/guides/create/parse-packageparameters-argument', '[Learn more](xref:parse-package-parameters)' - $text = $text -replace 'at https://docs.chocolatey.org/en-us/guides/create/parse-packageparameters-argument#step-3---use-core-community-extension', 'in [the docs](xref:parse-package-parameters#step-3-use-core-community-extension)' - $text = $text -replace 'https://docs.chocolatey.org/en-us/guides/create/parse-packageparameters-argument', 'https://docs.chocolatey.org/en-us/guides/create/parse-packageparameters-argument' - $text = $text -replace '\[community feed\)\]\(https://community.chocolatey.org/packages\)', '[community feed](https://community.chocolatey.org/packages))' - - Write-Output $text + $text = $text -replace '(community feed[s]?[^\]]|community repository)', '[$1](https://community.chocolatey.org/packages)' + $text = $text -replace '(Chocolatey for Business|Chocolatey Professional|Chocolatey Pro)(?=[^\w])', '[$1](https://chocolatey.org/compare)' + $text = $text -replace '(Pro[fessional]\s?/\s?Business)', '[$1](https://chocolatey.org/compare)' + $text = $text -replace '([Ll]icensed editions)', '[$1](https://chocolatey.org/compare)' + $text = $text -replace '([Ll]icensed versions)', '[$1](https://chocolatey.org/compare)' + $text = $text -replace '\(https://docs.chocolatey.org/en-us/create/automatic-packages\)', '(xref:automatic-packaging)' + $text = $text -replace 'Learn more about using this at https://docs.chocolatey.org/en-us/guides/create/parse-packageparameters-argument', '[Learn more](xref:parse-package-parameters)' + $text = $text -replace 'at https://docs.chocolatey.org/en-us/guides/create/parse-packageparameters-argument#step-3---use-core-community-extension', 'in [the docs](xref:parse-package-parameters#step-3-use-core-community-extension)' + $text = $text -replace 'https://docs.chocolatey.org/en-us/guides/create/parse-packageparameters-argument', 'https://docs.chocolatey.org/en-us/guides/create/parse-packageparameters-argument' + $text = $text -replace '\[community feed\)\]\(https://community.chocolatey.org/packages\)', '[community feed](https://community.chocolatey.org/packages))' + + Write-Output $text } function Convert-Syntax($objItem, $hasCmdletBinding) { - $cmd = $objItem.Name - - if ($objItem.parameter -ne $null) { - $objItem.parameter | ForEach-Object { - $cmd += ' `' + $lineFeed - $cmd += " " - if ($_.required -eq $false) { $cmd += '['} - $cmd += "-$($_.name.substring(0,1).toupper() + $_.name.substring(1))" - - - if ($_.parameterValue -ne $null) { $cmd += " <$($_.parameterValue)>" } - if ($_.parameterValueGroup -ne $null) { $cmd += " {" + ($_.parameterValueGroup.parameterValue -join ' | ') + "}"} - if ($_.required -eq $false) { $cmd += ']'} + $cmd = $objItem.Name + + if ($objItem.parameter -ne $null) { + $objItem.parameter | ForEach-Object { + $cmd += ' `' + $lineFeed + $cmd += " " + if ($_.required -eq $false) { + $cmd += '[' + } + $cmd += "-$($_.name.substring(0,1).toupper() + $_.name.substring(1))" + + + if ($_.parameterValue -ne $null) { + $cmd += " <$($_.parameterValue)>" + } + if ($_.parameterValueGroup -ne $null) { + $cmd += " {" + ($_.parameterValueGroup.parameterValue -join ' | ') + "}" + } + if ($_.required -eq $false) { + $cmd += ']' + } + } + } + if ($hasCmdletBinding) { + $cmd += " []" } - } - if ($hasCmdletBinding) { $cmd += " []"} - Write-Output "$lineFeed~~~powershell$lineFeed$($cmd)$lineFeed~~~" + Write-Output "$lineFeed~~~powershell$lineFeed$($cmd)$lineFeed~~~" } function Convert-Parameter($objItem, $commandName) { - $paramText = $lineFeed + "### -$($objItem.name.substring(0,1).ToUpper() + $objItem.name.substring(1))" - if ( ($objItem.parameterValue -ne $null) -and ($objItem.parameterValue -ne 'SwitchParameter') ) { - $paramText += ' ' - if ([string]($objItem.required) -eq 'false') { $paramText += "["} - $paramText += "<$($objItem.parameterValue)>" - if ([string]($objItem.required) -eq 'false') { $paramText += "]"} - } - $paramText += $lineFeed - if ($objItem.description -ne $null) { - $parmText += (($objItem.description | ForEach-Object { Replace-CommonItems $_.Text }) -join "$lineFeed") + $lineFeed + $lineFeed - } - if ($objItem.parameterValueGroup -ne $null) { - $paramText += "$($lineFeed)Valid options: " + ($objItem.parameterValueGroup.parameterValue -join ", ") + $lineFeed + $lineFeed - } - - $aliases = [string]((Get-Command -Name $commandName).parameters."$($objItem.Name)".Aliases -join ', ') - $required = [string]($objItem.required) - $position = [string]($objItem.position) - $defValue = [string]($objItem.defaultValue) - $acceptPipeline = [string]($objItem.pipelineInput) - - $padding = ($aliases.Length, $required.Length, $position.Length, $defValue.Length, $acceptPipeline.Length | Measure-Object -Maximum).Maximum + $paramText = $lineFeed + "### -$($objItem.name.substring(0,1).ToUpper() + $objItem.name.substring(1))" + if ( ($objItem.parameterValue -ne $null) -and ($objItem.parameterValue -ne 'SwitchParameter') ) { + $paramText += ' ' + if ([string]($objItem.required) -eq 'false') { + $paramText += "[" + } + $paramText += "<$($objItem.parameterValue)>" + if ([string]($objItem.required) -eq 'false') { + $paramText += "]" + } + } + $paramText += $lineFeed + if ($objItem.description -ne $null) { + $parmText += (($objItem.description | ForEach-Object { Replace-CommonItems $_.Text }) -join "$lineFeed") + $lineFeed + $lineFeed + } + if ($objItem.parameterValueGroup -ne $null) { + $paramText += "$($lineFeed)Valid options: " + ($objItem.parameterValueGroup.parameterValue -join ", ") + $lineFeed + $lineFeed + } + + $aliases = [string]((Get-Command -Name $commandName).parameters."$($objItem.Name)".Aliases -join ', ') + $required = [string]($objItem.required) + $position = [string]($objItem.position) + $defValue = [string]($objItem.defaultValue) + $acceptPipeline = [string]($objItem.pipelineInput) + + $padding = ($aliases.Length, $required.Length, $position.Length, $defValue.Length, $acceptPipeline.Length | Measure-Object -Maximum).Maximum $paramText += @" Property | Value @@ -195,58 +211,58 @@ Accept Pipeline Input? | $($acceptPipeline) "@ - Write-Output $paramText + Write-Output $paramText } function Convert-CommandText { -param( - [string]$commandText, - [string]$commandName = '' -) - if ( $commandText -match '^\s?NOTE: Options and switches apply to all items passed, so if you are\s?$' ` - -or $commandText -match '^\s?installing multiple packages, and you use \`\-\-version\=1\.0\.0\`, it is\s?$' ` - -or $commandText -match '^\s?going to look for and try to install version 1\.0\.0 of every package\s?$' ` - -or $commandText -match '^\s?passed\. So please split out multiple package calls when wanting to\s?$' ` - -or $commandText -match '^\s?pass specific options\.\s?$' ` - ) { - return - } - $commandText = $commandText -creplace '^(.+)(\s+Command\s*)$', "# `$1`$2 (choco $commandName)" - $commandText = $commandText -creplace '^(DEPRECATION NOTICE|Usage|Troubleshooting|Examples|Exit Codes|Connecting to Chocolatey.org|See It In Action|Alternative Sources|Resources|Packages.config|Scripting \/ Integration - Best Practices \/ Style Guide)', '## $1' - $commandText = $commandText -replace '^(Commands|How To Pass Options)', '## $1' - $commandText = $commandText -replace '^(WebPI|Windows Features|Ruby|Cygwin|Python)\s*$', '### $1' - $commandText = $commandText -replace '(? :choco-info: **NOTE**' - $commandText = $commandText -replace '\*> :choco-info: \*\*NOTE\*\*\*', '> :choco-info: **NOTE**' - $commandText = $commandText -replace 'the command reference', '[how to pass arguments](xref:choco-commands#how-to-pass-options-switches)' - $commandText = $commandText -replace '(community feed[s]?|community repository)', '[$1](https://community.chocolatey.org/packages)' - #$commandText = $commandText -replace '\`(apikey|install|upgrade|uninstall|list|search|info|outdated|pin)\`', '[[`$1`|Commands$1]]' - $commandText = $commandText -replace '\`([choco\s]*)(apikey|install|upgrade|uninstall|list|search|info|outdated|pin)\`', '[`$1$2`](xref:choco-command-$2)' - $commandText = $commandText -replace '^(.+):\s(.+.gif)$', '![$1]($2)' - $commandText = $commandText -replace '^(\s+)\<\?xml', "~~~xml$lineFeed`$1', "`$1$lineFeed~~~" - $commandText = $commandText -replace '(Chocolatey for Business|Chocolatey Professional|Chocolatey Pro)(?=[^\w])', '[$1](https://chocolatey.org/compare)' - $commandText = $commandText -replace '(Pro[fessional]\s?/\s?Business)', '[$1](https://chocolatey.org/compare)' - $commandText = $commandText -replace '([Ll]icensed editions)', '[$1](https://chocolatey.org/compare)' - $commandText = $commandText -replace '([Ll]icensed versions)', '[$1](https://chocolatey.org/compare)' - $commandText = $commandText -replace 'https://raw.githubusercontent.com/wiki/chocolatey/choco/images', '/assets/images' - $commandText = $commandText -replace 'https://chocolatey.org/docs/features-automatically-recompile-packages', 'https://docs.chocolatey.org/en-us/guides/create/recompile-packages' - $commandText = $commandText -replace 'https://chocolatey.org/docs/features-private-cdn', 'https://docs.chocolatey.org/en-us/features/private-cdn' - $commandText = $commandText -replace 'https://chocolatey.org/docs/features-virus-check', 'https://docs.chocolatey.org/en-us/features/virus-check' - $commandText = $commandText -replace 'https://chocolatey.org/docs/features-synchronize', 'https://docs.chocolatey.org/en-us/features/package-synchronization' - $commandText = $commandText -replace 'explicity', 'explicit' - $commandText = $commandText -replace 'https://chocolatey.org/docs/features-create-packages-from-installers', 'https://docs.chocolatey.org/en-us/features/package-builder' - $commandText = $commandText -replace 'See https://chocolatey.org/docs/features-create-packages-from-installers', 'See more information about [Package Builder features](xref:package-builder)' - $commandText = $commandText -replace 'See https://docs.chocolatey.org/en-us/features/package-builder', 'See more information about [Package Builder features](xref:package-builder)' - $commandText = $commandText -replace 'https://chocolatey.org/docs/features-install-directory-override', 'https://docs.chocolatey.org/en-us/features/install-directory-override' - $commandText = $commandText -replace 'y.org/docs/features-package-reducer', 'y.org/docs/en-us/features/package-reducer' - $commandText = $commandText -replace 'https://chocolatey.org/docs/features-package-reducer', 'https://docs.chocolatey.org/en-us/features/package-reducer' - $commandText = $commandText -replace 'https://chocolatey.org/docs/en-us/features/package-reducer', 'https://docs.chocolatey.org/en-us/features/package-reducer' - $commandText = $commandText -replace '\[community feed\)\]\(https://community.chocolatey.org/packages\)', '[community feed](https://community.chocolatey.org/packages))' + param( + [string]$commandText, + [string]$commandName = '' + ) + if ( $commandText -match '^\s?NOTE: Options and switches apply to all items passed, so if you are\s?$' ` + -or $commandText -match '^\s?installing multiple packages, and you use \`\-\-version\=1\.0\.0\`, it is\s?$' ` + -or $commandText -match '^\s?going to look for and try to install version 1\.0\.0 of every package\s?$' ` + -or $commandText -match '^\s?passed\. So please split out multiple package calls when wanting to\s?$' ` + -or $commandText -match '^\s?pass specific options\.\s?$' ` + ) { + return + } + $commandText = $commandText -creplace '^(.+)(\s+Command\s*)$', "# `$1`$2 (choco $commandName)" + $commandText = $commandText -creplace '^(DEPRECATION NOTICE|Usage|Troubleshooting|Examples|Exit Codes|Connecting to Chocolatey.org|See It In Action|Alternative Sources|Resources|Packages.config|Scripting \/ Integration - Best Practices \/ Style Guide)', '## $1' + $commandText = $commandText -replace '^(Commands|How To Pass Options)', '## $1' + $commandText = $commandText -replace '^(WebPI|Windows Features|Ruby|Cygwin|Python)\s*$', '### $1' + $commandText = $commandText -replace '(? :choco-info: **NOTE**' + $commandText = $commandText -replace '\*> :choco-info: \*\*NOTE\*\*\*', '> :choco-info: **NOTE**' + $commandText = $commandText -replace 'the command reference', '[how to pass arguments](xref:choco-commands#how-to-pass-options-switches)' + $commandText = $commandText -replace '(community feed[s]?|community repository)', '[$1](https://community.chocolatey.org/packages)' + #$commandText = $commandText -replace '\`(apikey|install|upgrade|uninstall|list|search|info|outdated|pin)\`', '[[`$1`|Commands$1]]' + $commandText = $commandText -replace '\`([choco\s]*)(apikey|install|upgrade|uninstall|list|search|info|outdated|pin)\`', '[`$1$2`](xref:choco-command-$2)' + $commandText = $commandText -replace '^(.+):\s(.+.gif)$', '![$1]($2)' + $commandText = $commandText -replace '^(\s+)\<\?xml', "~~~xml$lineFeed`$1', "`$1$lineFeed~~~" + $commandText = $commandText -replace '(Chocolatey for Business|Chocolatey Professional|Chocolatey Pro)(?=[^\w])', '[$1](https://chocolatey.org/compare)' + $commandText = $commandText -replace '(Pro[fessional]\s?/\s?Business)', '[$1](https://chocolatey.org/compare)' + $commandText = $commandText -replace '([Ll]icensed editions)', '[$1](https://chocolatey.org/compare)' + $commandText = $commandText -replace '([Ll]icensed versions)', '[$1](https://chocolatey.org/compare)' + $commandText = $commandText -replace 'https://raw.githubusercontent.com/wiki/chocolatey/choco/images', '/assets/images' + $commandText = $commandText -replace 'https://chocolatey.org/docs/features-automatically-recompile-packages', 'https://docs.chocolatey.org/en-us/guides/create/recompile-packages' + $commandText = $commandText -replace 'https://chocolatey.org/docs/features-private-cdn', 'https://docs.chocolatey.org/en-us/features/private-cdn' + $commandText = $commandText -replace 'https://chocolatey.org/docs/features-virus-check', 'https://docs.chocolatey.org/en-us/features/virus-check' + $commandText = $commandText -replace 'https://chocolatey.org/docs/features-synchronize', 'https://docs.chocolatey.org/en-us/features/package-synchronization' + $commandText = $commandText -replace 'explicity', 'explicit' + $commandText = $commandText -replace 'https://chocolatey.org/docs/features-create-packages-from-installers', 'https://docs.chocolatey.org/en-us/features/package-builder' + $commandText = $commandText -replace 'See https://chocolatey.org/docs/features-create-packages-from-installers', 'See more information about [Package Builder features](xref:package-builder)' + $commandText = $commandText -replace 'See https://docs.chocolatey.org/en-us/features/package-builder', 'See more information about [Package Builder features](xref:package-builder)' + $commandText = $commandText -replace 'https://chocolatey.org/docs/features-install-directory-override', 'https://docs.chocolatey.org/en-us/features/install-directory-override' + $commandText = $commandText -replace 'y.org/docs/features-package-reducer', 'y.org/docs/en-us/features/package-reducer' + $commandText = $commandText -replace 'https://chocolatey.org/docs/features-package-reducer', 'https://docs.chocolatey.org/en-us/features/package-reducer' + $commandText = $commandText -replace 'https://chocolatey.org/docs/en-us/features/package-reducer', 'https://docs.chocolatey.org/en-us/features/package-reducer' + $commandText = $commandText -replace '\[community feed\)\]\(https://community.chocolatey.org/packages\)', '[community feed](https://community.chocolatey.org/packages))' $commandText = $commandText -replace '> :choco-info: \*\*NOTE\*\*\s', '> :choco-info: **NOTE** > > ' - $optionsSwitches = @' + $optionsSwitches = @' ## $1 > :choco-info: **NOTE** @@ -262,9 +278,9 @@ Includes [default options/switches](xref:choco-commands#default-options-and-swit ~~~ '@ - $commandText = $commandText -replace '^(Options and Switches)', $optionsSwitches + $commandText = $commandText -replace '^(Options and Switches)', $optionsSwitches - $optionsSwitches = @' + $optionsSwitches = @' ## $1 > :choco-info: **NOTE** @@ -278,98 +294,103 @@ Includes [default options/switches](xref:choco-commands#default-options-and-swit ~~~ '@ - $commandText = $commandText -replace '^(Default Options and Switches)', $optionsSwitches + $commandText = $commandText -replace '^(Default Options and Switches)', $optionsSwitches - Write-Output $commandText + Write-Output $commandText } function Convert-CommandReferenceSpecific($commandText) { - $commandText = [Regex]::Replace($commandText, '\s?\s?\*\s(\w+)\s\-', - { - param($m) - $commandName = $m.Groups[1].Value - $commandNameUpper = $($commandName.Substring(0,1).ToUpper() + $commandName.Substring(1)) - " * [$commandName](xref:choco-command-$($commandName)) -" - } - ) - #$commandText = $commandText -replace '\s?\s?\*\s(\w+)\s\-', ' * [[$1|Commands$1]] -' - $commandText = $commandText.Replace("## Default Options and Switches", "## See Help Menu In Action$lineFeed$lineFeed![choco help in action](/assets/images/gifs/choco_help.gif)$lineFeed$lineFeed## Default Options and Switches") - - Write-Output $commandText + $commandText = [Regex]::Replace($commandText, '\s?\s?\*\s(\w+)\s\-', + { + param($m) + $commandName = $m.Groups[1].Value + $commandNameUpper = $($commandName.Substring(0, 1).ToUpper() + $commandName.Substring(1)) + " * [$commandName](xref:choco-command-$($commandName)) -" + } + ) + #$commandText = $commandText -replace '\s?\s?\*\s(\w+)\s\-', ' * [[$1|Commands$1]] -' + $commandText = $commandText.Replace("## Default Options and Switches", "## See Help Menu In Action$lineFeed$lineFeed![choco help in action](/assets/images/gifs/choco_help.gif)$lineFeed$lineFeed## Default Options and Switches") + + Write-Output $commandText } function Generate-TopLevelCommandReference { - Write-Host "Generating Top Level Command Reference" - $fileName = "$docsFolder\choco\commands\index.md" - $commandOutput = @("---") - $commandOutput += @("Order: 40") - $commandOutput += @("xref: choco-commands") - $commandOutput += @("Title: Commands") - $commandOutput += @("Description: Full list of all available Chocolatey commands") - $commandOutput += @("RedirectFrom:") - $commandOutput += @(" - docs/commandsreference") - $commandOutput += @(" - docs/commands-reference") - $commandOutput += @("---$lineFeed") - $commandOutput += @("# Command Reference$lineFeed") - $commandOutput += @(" $lineFeed") - $commandOutput += $(& $chocoExe -? -r) - $commandOutput += @("$lineFeed~~~$lineFeed") - $commandOutput += @("$lineFeed$lineFeed*NOTE:* This documentation has been automatically generated from ``choco -h``. $lineFeed") - - $commandOutput | - ForEach-Object { Convert-CommandText($_) } | - ForEach-Object { Convert-CommandReferenceSpecific($_) } | - Out-File $fileName -Encoding UTF8 -Force + Write-Host "Generating Top Level Command Reference" + $fileName = "$docsFolder\choco\commands\index.md" + $commandOutput = @("---") + $commandOutput += @("Order: 40") + $commandOutput += @("xref: choco-commands") + $commandOutput += @("Title: Commands") + $commandOutput += @("Description: Full list of all available Chocolatey commands") + $commandOutput += @("RedirectFrom:") + $commandOutput += @(" - docs/commandsreference") + $commandOutput += @(" - docs/commands-reference") + $commandOutput += @("---$lineFeed") + $commandOutput += @("# Command Reference$lineFeed") + $commandOutput += @(" $lineFeed") + $commandOutput += $(& $chocoExe -? -r) + $commandOutput += @("$lineFeed~~~$lineFeed") + $commandOutput += @("$lineFeed$lineFeed*NOTE:* This documentation has been automatically generated from ``choco -h``. $lineFeed") + + $commandOutput | + ForEach-Object { Convert-CommandText($_) } | + ForEach-Object { Convert-CommandReferenceSpecific($_) } | + Out-File $fileName -Encoding UTF8 -Force } function Move-GeneratedFiles { - if(-not(Test-Path "$docsFolder\create\commands")){ mkdir "$docsFolder\create\commands" -EA Continue | Out-Null } - - Move-Item -Path "$docsFolder\choco\commands\apikey.md" -Destination "$docsFolder\create\commands\api-key.md" - Move-Item -Path "$docsFolder\choco\commands\new.md" -Destination "$docsFolder\create\commands\new.md" - Move-Item -Path "$docsFolder\choco\commands\pack.md" -Destination "$docsFolder\create\commands\pack.md" - Move-Item -Path "$docsFolder\choco\commands\push.md" -Destination "$docsFolder\create\commands\push.md" - Move-Item -Path "$docsFolder\choco\commands\template.md" -Destination "$docsFolder\create\commands\template.md" - Move-Item -Path "$docsFolder\choco\commands\templates.md" -Destination "$docsFolder\create\commands\templates.md" - Move-Item -Path "$docsFolder\choco\commands\convert.md" -Destination "$docsFolder\create\commands\convert.md" + if (-not(Test-Path "$docsFolder\create\commands")) { + New-Item -ItemType Directory -Path "$docsFolder\create\commands" -ErrorAction Continue | Out-Null + } + + Move-Item -Path "$docsFolder\choco\commands\apikey.md" -Destination "$docsFolder\create\commands\api-key.md" + Move-Item -Path "$docsFolder\choco\commands\new.md" -Destination "$docsFolder\create\commands\new.md" + Move-Item -Path "$docsFolder\choco\commands\pack.md" -Destination "$docsFolder\create\commands\pack.md" + Move-Item -Path "$docsFolder\choco\commands\push.md" -Destination "$docsFolder\create\commands\push.md" + Move-Item -Path "$docsFolder\choco\commands\template.md" -Destination "$docsFolder\create\commands\template.md" + Move-Item -Path "$docsFolder\choco\commands\templates.md" -Destination "$docsFolder\create\commands\templates.md" + Move-Item -Path "$docsFolder\choco\commands\convert.md" -Destination "$docsFolder\create\commands\convert.md" } function Generate-CommandReference($commandName, $order) { - if(-not(Test-Path "$docsFolder\choco\commands")){ mkdir "$docsFolder\choco\commands" -EA Continue | Out-Null } - $fileName = Join-Path "$docsFolder\choco\commands" "$($commandName.ToLower()).md" - $commandNameLower = $commandName.ToLower() - - Write-Host "Generating $fileName ..." - $commandOutput += @("---") - $commandOutput += @("Order: $order") - $commandOutput += @("xref: choco-command-$commandNameLower") - - if($commandName -eq 'List') { - $commandOutput += @("Title: $commandName/Search") - $commandOutput += @("Description: $commandName/Search Command (choco $commandNameLower)") - } else { - $commandOutput += @("Title: $commandName") - $commandOutput += @("Description: $commandName Command (choco $commandNameLower)") - } - - $commandOutput += @("RedirectFrom:") - $commandOutput += @(" - docs/commands$commandNameLower") - $commandOutput += @(" - docs/commands-$commandNameLower") - - if($commandName -eq 'Features') { - $commandOutput += @("ShowInNavbar: false") - $commandOutput += @("ShowInSidebar: false") - } - - if($commandName -eq 'Templates') { - $commandOutput += @("ShowInNavbar: false") - $commandOutput += @("ShowInSidebar: false") - } - - $commandOutput += @("---$lineFeed") - $commandOutput += @(" $lineFeed") - - $commandOutput += @(@" + if (-not(Test-Path "$docsFolder\choco\commands")) { + New-Item -ItemType Directory -Path "$docsFolder\choco\commands" -ErrorAction Continue | Out-Null + } + $fileName = Join-Path "$docsFolder\choco\commands" "$($commandName.ToLower()).md" + $commandNameLower = $commandName.ToLower() + + Write-Host "Generating $fileName ..." + $commandOutput += @("---") + $commandOutput += @("Order: $order") + $commandOutput += @("xref: choco-command-$commandNameLower") + + if ($commandName -eq 'List') { + $commandOutput += @("Title: $commandName/Search") + $commandOutput += @("Description: $commandName/Search Command (choco $commandNameLower)") + } + else { + $commandOutput += @("Title: $commandName") + $commandOutput += @("Description: $commandName Command (choco $commandNameLower)") + } + + $commandOutput += @("RedirectFrom:") + $commandOutput += @(" - docs/commands$commandNameLower") + $commandOutput += @(" - docs/commands-$commandNameLower") + + if ($commandName -eq 'Features') { + $commandOutput += @("ShowInNavbar: false") + $commandOutput += @("ShowInSidebar: false") + } + + if ($commandName -eq 'Templates') { + $commandOutput += @("ShowInNavbar: false") + $commandOutput += @("ShowInSidebar: false") + } + + $commandOutput += @("---$lineFeed") + $commandOutput += @(" $lineFeed") + + $commandOutput += @(@" > :choco-warning: **WARNING** SHIM DEPRECATION > > With the release of Chocolatey CLI v1.0.0 we have deprecated the following shims/shortcuts: @@ -385,49 +406,56 @@ function Generate-CommandReference($commandName, $order) { "@) - $commandOutput += $(& $chocoExe $commandName.ToLower() -h -r) - $commandOutput += @("$lineFeed~~~$lineFeed$lineFeed[Command Reference](xref:choco-commands)") - $commandOutput += @("$lineFeed$lineFeed*NOTE:* This documentation has been automatically generated from ``choco $($commandName.ToLower()) -h``. $lineFeed") - $commandOutput | - ForEach-Object { Convert-CommandText $_ $commandName.ToLower() } | - Out-File $fileName -Encoding UTF8 -Force + $commandOutput += $(& $chocoExe $commandName.ToLower() -h -r) + $commandOutput += @("$lineFeed~~~$lineFeed$lineFeed[Command Reference](xref:choco-commands)") + $commandOutput += @("$lineFeed$lineFeed*NOTE:* This documentation has been automatically generated from ``choco $($commandName.ToLower()) -h``. $lineFeed") + $commandOutput | + ForEach-Object { Convert-CommandText $_ $commandName.ToLower() } | + Out-File $fileName -Encoding UTF8 -Force } -try -{ - Write-Host "Importing the Module $psModuleName ..." - Import-Module "$psModuleLocation" -Force -Verbose - - # Switch Get-PackageParameters back for documentation - Remove-Item alias:Get-PackageParameters - Remove-Item function:Get-PackageParametersBuiltIn - Set-Alias -Name Get-PackageParametersBuiltIn -Value Get-PackageParameters -Scope Global +try { + Write-Host "Importing the Module $psModuleName ..." + Import-Module "$psModuleLocation" -Force -Verbose - if (Test-Path($docsFolder)) { Remove-Item $docsFolder -Force -Recurse -EA SilentlyContinue } - if(-not(Test-Path $docsFolder)){ mkdir $docsFolder -EA Continue | Out-Null } - if(-not(Test-Path "$docsFolder\create\functions")){ mkdir "$docsFolder\create\functions" -EA Continue | Out-Null } + # Switch Get-PackageParameters back for documentation + Remove-Item alias:Get-PackageParameters + Remove-Item function:Get-PackageParametersBuiltIn + Set-Alias -Name Get-PackageParametersBuiltIn -Value Get-PackageParameters -Scope Global - Write-Host 'Creating per PowerShell function markdown files...' - $helperOrder = 10; - Get-Command -Module $psModuleName -CommandType Function | ForEach-Object -Process { Get-Help $_ -Full } | ForEach-Object -Process { ` - $commandName = $_.Name - $fileName = Join-Path "$docsFolder\create\functions" "$($_.Name.ToLower()).md" - $global:powerShellReferenceTOC += "$lineFeed * [$commandName](xref:$([System.IO.Path]::GetFileNameWithoutExtension($fileName)))" - $hasCmdletBinding = (Get-Command -Name $commandName).CmdLetBinding - - Write-Host "Generating $fileName ..." - $SplitName = $_.Name -split "-" - $NameNoHyphen = $_.Name -replace '-', '' - - if($_.Name -eq 'Get-OSArchitectureWidth') { - $FormattedName = "get-os-architecture-width" - } elseif($_.Name -eq 'Get-UACEnabled') { - $FormattedName = "get-uac-enabled" - }else { - $FormattedName = $SplitName[0].ToLower() + ($SplitName[1] -creplace '[A-Z]', '-$&').ToLower() + if (Test-Path($docsFolder)) { + Remove-Item $docsFolder -Force -Recurse -ErrorAction SilentlyContinue + } + if (-not(Test-Path $docsFolder)) { + New-Item -ItemType Directory -Path $docsFolder -ErrorAction Continue | Out-Null + } + if (-not(Test-Path "$docsFolder\create\functions")) { + New-Item -ItemType Directory -Path "$docsFolder\create\functions" -ErrorAction Continue | Out-Null } - @" + Write-Host 'Creating per PowerShell function markdown files...' + $helperOrder = 10; + Get-Command -Module $psModuleName -CommandType Function | ForEach-Object -Process { Get-Help $_ -Full } | ForEach-Object -Process { ` + $commandName = $_.Name + $fileName = Join-Path "$docsFolder\create\functions" "$($_.Name.ToLower()).md" + $global:powerShellReferenceTOC += "$lineFeed * [$commandName](xref:$([System.IO.Path]::GetFileNameWithoutExtension($fileName)))" + $hasCmdletBinding = (Get-Command -Name $commandName).CmdLetBinding + + Write-Host "Generating $fileName ..." + $SplitName = $_.Name -split "-" + $NameNoHyphen = $_.Name -replace '-', '' + + if ($_.Name -eq 'Get-OSArchitectureWidth') { + $FormattedName = "get-os-architecture-width" + } + elseif ($_.Name -eq 'Get-UACEnabled') { + $FormattedName = "get-uac-enabled" + } + else { + $FormattedName = $SplitName[0].ToLower() + ($SplitName[1] -creplace '[A-Z]', '-$&').ToLower() + } + + @" --- Order: $($helperOrder) xref: $($_.Name.ToLower()) @@ -474,13 +502,13 @@ $( if ($_.relatedLinks -ne $null) {Write-Output "$lineFeed## Links$lineFeed$line View the source for [$($_.Name)]($sourceFunctions/$($_.Name)`.ps1) "@ | Out-File $fileName -Encoding UTF8 -Force - $helperOrder = $helperOrder + 10 - } + $helperOrder = $helperOrder + 10 + } - Write-Host "Generating Top Level PowerShell Reference" - $fileName = Join-Path "$docsFolder\create\functions" 'index.md' + Write-Host "Generating Top Level PowerShell Reference" + $fileName = Join-Path "$docsFolder\create\functions" 'index.md' - $global:powerShellReferenceTOC += @' + $global:powerShellReferenceTOC += @' ## Chocolatey for Business Functions @@ -568,48 +596,47 @@ The following are experimental or use not recommended: * ChocolateyToolsLocation - Not for use in package automation scripts. Recommend using Get-ToolsLocation instead '@ - $global:powerShellReferenceTOC | Out-File $fileName -Encoding UTF8 -Force - - Write-Host "Generating command reference markdown files" - Generate-CommandReference 'Config' '10' - Generate-CommandReference 'Download' '20' - Generate-CommandReference 'Export' '30' - Generate-CommandReference 'Find' '35' - Generate-CommandReference 'Feature' '40' - Generate-CommandReference 'Features' '45' - Generate-CommandReference 'Help' '50' - Generate-CommandReference 'Info' '60' - Generate-CommandReference 'Install' '70' - Generate-CommandReference 'List' '80' - Generate-CommandReference 'Optimize' '90' - Generate-CommandReference 'Outdated' '100' - Generate-CommandReference 'Pin' '110' - Generate-CommandReference 'Search' '120' - Generate-CommandReference 'SetApiKey' '130' - Generate-CommandReference 'Source' '140' - Generate-CommandReference 'Sources' '150' - Generate-CommandReference 'Support' '160' - Generate-CommandReference 'Sync' '170' - Generate-CommandReference 'Synchronize' '180' - Generate-CommandReference 'Uninstall' '190' - Generate-CommandReference 'UnpackSelf' '200' - Generate-CommandReference 'Upgrade' '220' - - Generate-CommandReference 'New' '10' - Generate-CommandReference 'Pack' '20' - Generate-CommandReference 'ApiKey' '30' - Generate-CommandReference 'Push' '40' - Generate-CommandReference 'Template' '50' - Generate-CommandReference 'Templates' '55' - Generate-CommandReference 'Convert' '60' - - Generate-TopLevelCommandReference - Move-GeneratedFiles - - Exit 0 + $global:powerShellReferenceTOC | Out-File $fileName -Encoding UTF8 -Force + + Write-Host "Generating command reference markdown files" + Generate-CommandReference 'Config' '10' + Generate-CommandReference 'Download' '20' + Generate-CommandReference 'Export' '30' + Generate-CommandReference 'Find' '35' + Generate-CommandReference 'Feature' '40' + Generate-CommandReference 'Features' '45' + Generate-CommandReference 'Help' '50' + Generate-CommandReference 'Info' '60' + Generate-CommandReference 'Install' '70' + Generate-CommandReference 'List' '80' + Generate-CommandReference 'Optimize' '90' + Generate-CommandReference 'Outdated' '100' + Generate-CommandReference 'Pin' '110' + Generate-CommandReference 'Search' '120' + Generate-CommandReference 'SetApiKey' '130' + Generate-CommandReference 'Source' '140' + Generate-CommandReference 'Sources' '150' + Generate-CommandReference 'Support' '160' + Generate-CommandReference 'Sync' '170' + Generate-CommandReference 'Synchronize' '180' + Generate-CommandReference 'Uninstall' '190' + Generate-CommandReference 'UnpackSelf' '200' + Generate-CommandReference 'Upgrade' '220' + + Generate-CommandReference 'New' '10' + Generate-CommandReference 'Pack' '20' + Generate-CommandReference 'ApiKey' '30' + Generate-CommandReference 'Push' '40' + Generate-CommandReference 'Template' '50' + Generate-CommandReference 'Templates' '55' + Generate-CommandReference 'Convert' '60' + + Generate-TopLevelCommandReference + Move-GeneratedFiles + + Exit 0 } -catch -{ - Throw "Failed to generate documentation. $_" - Exit 255 +catch { + Throw "Failed to generate documentation. $_" + Exit 255 } diff --git a/Invoke-Tests.ps1 b/Invoke-Tests.ps1 index b138284035..7a067a56f4 100644 --- a/Invoke-Tests.ps1 +++ b/Invoke-Tests.ps1 @@ -1,4 +1,4 @@ -#Requires -Module @{ ModuleName = 'pester'; ModuleVersion = '5.3.1' } +#Requires -Module @{ ModuleName = 'pester'; ModuleVersion = '5.3.1' } #Requires -RunAsAdministrator <# .SYNOPSIS @@ -121,7 +121,6 @@ try { } Invoke-Pester -Configuration $PesterConfiguration - } finally { # For some reason we need to import this again... I'm not 100% sure on why... diff --git a/ScriptFormat.Tests.ps1 b/ScriptFormat.Tests.ps1 index 603190b686..de6c65113a 100644 --- a/ScriptFormat.Tests.ps1 +++ b/ScriptFormat.Tests.ps1 @@ -45,21 +45,31 @@ Describe "Verifying integrity of module files" { ) if ($PSVersionTable.PSVersion.Major -lt 6) { - [byte[]]$byte = get-content -Encoding byte -ReadCount 4 -TotalCount 4 -Path $Path + [byte[]]$byte = Get-Content -Encoding byte -ReadCount 4 -TotalCount 4 -Path $Path } else { [byte[]]$byte = Get-Content -AsByteStream -ReadCount 4 -TotalCount 4 -Path $Path } - if ($byte[0] -eq 0xef -and $byte[1] -eq 0xbb -and $byte[2] -eq 0xbf) { 'UTF8 BOM' } - elseif ($byte[0] -eq 0xfe -and $byte[1] -eq 0xff) { 'Unicode' } - elseif ($byte[0] -eq 0 -and $byte[1] -eq 0 -and $byte[2] -eq 0xfe -and $byte[3] -eq 0xff) { 'UTF32' } - elseif ($byte[0] -eq 0x2b -and $byte[1] -eq 0x2f -and $byte[2] -eq 0x76) { 'UTF7' } - else { 'Unknown' } + if ($byte[0] -eq 0xef -and $byte[1] -eq 0xbb -and $byte[2] -eq 0xbf) { + 'UTF8 BOM' + } + elseif ($byte[0] -eq 0xfe -and $byte[1] -eq 0xff) { + 'Unicode' + } + elseif ($byte[0] -eq 0 -and $byte[1] -eq 0 -and $byte[2] -eq 0xfe -and $byte[3] -eq 0xff) { + 'UTF32' + } + elseif ($byte[0] -eq 0x2b -and $byte[1] -eq 0x2f -and $byte[2] -eq 0x76) { + 'UTF7' + } + else { + 'Unknown' + } } } - Context "Validating PowerShell file <_.FullName>" -Foreach $FilesBeingTested { + Context "Validating PowerShell file <_.FullName>" -ForEach $FilesBeingTested { BeforeAll { $FileUnderTest = $_ } diff --git a/build.ps1 b/build.ps1 index adfb2811aa..0b345bfcab 100644 --- a/build.ps1 +++ b/build.ps1 @@ -46,7 +46,7 @@ Param( [Alias("WhatIf", "Noop")] [switch]$DryRun, [switch]$SkipToolPackageRestore, - [Parameter(Position=0,Mandatory=$false,ValueFromRemainingArguments=$true)] + [Parameter(Position = 0, Mandatory = $false, ValueFromRemainingArguments = $true)] [string[]]$ScriptArgs ) @@ -54,44 +54,38 @@ Param( # PowerShell will not set this by default (until maybe .NET 4.6.x). This # will typically produce a message for PowerShell v2 (just an info # message though) -try -{ +try { # Set TLS 1.2 (3072), then TLS 1.1 (768), then TLS 1.0 (192), finally SSL 3.0 (48) # Use integers because the enumeration values for TLS 1.2 and TLS 1.1 won't # exist in .NET 4.0, even though they are addressable if .NET 4.5+ is # installed (.NET 4.5 is an in-place upgrade). [System.Net.ServicePointManager]::SecurityProtocol = 3072 -bor 768 -bor 192 -} catch { +} +catch { Write-Output 'Unable to set PowerShell to use TLS 1.2 and TLS 1.1 due to old .NET Framework installed. If you see underlying connection closed or trust errors, you may need to upgrade to .NET Framework 4.5+ and PowerShell v3' } [Reflection.Assembly]::LoadWithPartialName("System.Security") | Out-Null -function MD5HashFile([string] $filePath) -{ - if ([string]::IsNullOrEmpty($filePath) -or !(Test-Path $filePath -PathType Leaf)) - { +function MD5HashFile([string] $filePath) { + if ([string]::IsNullOrEmpty($filePath) -or !(Test-Path $filePath -PathType Leaf)) { return $null } [System.IO.Stream] $file = $null; [System.Security.Cryptography.MD5] $md5 = $null; - try - { + try { $md5 = [System.Security.Cryptography.MD5]::Create() $file = [System.IO.File]::OpenRead($filePath) return [System.BitConverter]::ToString($md5.ComputeHash($file)) } - finally - { - if ($file -ne $null) - { + finally { + if ($file -ne $null) { $file.Dispose() } } } -function GetProxyEnabledWebClient -{ +function GetProxyEnabledWebClient { $wc = New-Object System.Net.WebClient $proxy = [System.Net.WebRequest]::GetSystemWebProxy() $proxy.Credentials = [System.Net.CredentialCache]::DefaultCredentials @@ -101,7 +95,7 @@ function GetProxyEnabledWebClient Write-Host "Preparing to run build script..." -if(!$PSScriptRoot){ +if (!$PSScriptRoot) { $PSScriptRoot = Split-Path $MyInvocation.MyCommand.Path -Parent } @@ -119,7 +113,7 @@ $MODULES_PACKAGES_CONFIG = Join-Path $MODULES_DIR "packages.config" # Make sure tools folder exists if ((Test-Path $PSScriptRoot) -and !(Test-Path $TOOLS_DIR)) { Write-Verbose -Message "Creating tools directory..." - New-Item -Path $TOOLS_DIR -Type directory | out-null + New-Item -Path $TOOLS_DIR -Type directory | Out-Null } # Make sure that packages.config exist. @@ -128,7 +122,8 @@ if (!(Test-Path $PACKAGES_CONFIG)) { try { $wc = GetProxyEnabledWebClient $wc.DownloadFile("https://cakebuild.net/download/bootstrapper/packages", $PACKAGES_CONFIG) - } catch { + } + catch { Throw "Could not download packages.config." } } @@ -137,7 +132,7 @@ if (!(Test-Path $PACKAGES_CONFIG)) { if (!(Test-Path $NUGET_EXE)) { Write-Verbose -Message "Trying to find nuget.exe in PATH..." $existingPaths = $Env:Path -Split ';' | Where-Object { (![string]::IsNullOrEmpty($_)) -and (Test-Path $_ -PathType Container) } - $NUGET_EXE_IN_PATH = Get-ChildItem -Path $existingPaths -Filter "nuget.exe" | Select -First 1 + $NUGET_EXE_IN_PATH = Get-ChildItem -Path $existingPaths -Filter "nuget.exe" | Select-Object -First 1 if ($NUGET_EXE_IN_PATH -ne $null -and (Test-Path $NUGET_EXE_IN_PATH.FullName)) { Write-Verbose -Message "Found in PATH at $($NUGET_EXE_IN_PATH.FullName)." $NUGET_EXE = $NUGET_EXE_IN_PATH.FullName @@ -150,7 +145,8 @@ if (!(Test-Path $NUGET_EXE)) { try { $wc = GetProxyEnabledWebClient $wc.DownloadFile($NUGET_URL, $NUGET_EXE) - } catch { + } + catch { Throw "Could not download NuGet.exe." } } @@ -159,17 +155,17 @@ if (!(Test-Path $NUGET_EXE)) { $ENV:NUGET_EXE = $NUGET_EXE # Restore tools from NuGet? -if(-Not $SkipToolPackageRestore.IsPresent) { +if (-Not $SkipToolPackageRestore.IsPresent) { Push-Location Set-Location $TOOLS_DIR # Check for changes in packages.config and remove installed tools if true. [string] $md5Hash = MD5HashFile($PACKAGES_CONFIG) - if((!(Test-Path $PACKAGES_CONFIG_MD5)) -Or + if ((!(Test-Path $PACKAGES_CONFIG_MD5)) -Or ($md5Hash -ne (Get-Content $PACKAGES_CONFIG_MD5 ))) { Write-Verbose -Message "Missing or changed package.config hash..." - Get-ChildItem -Exclude packages.config,nuget.exe,Cake.Bakery | - Remove-Item -Recurse + Get-ChildItem -Exclude packages.config, nuget.exe, Cake.Bakery | + Remove-Item -Recurse } Write-Verbose -Message "Restoring tools from NuGet..." @@ -178,11 +174,10 @@ if(-Not $SkipToolPackageRestore.IsPresent) { if ($LASTEXITCODE -ne 0) { Throw "An error occurred while restoring NuGet tools." } - else - { + else { $md5Hash | Out-File $PACKAGES_CONFIG_MD5 -Encoding "ASCII" } - Write-Verbose -Message ($NuGetOutput | out-string) + Write-Verbose -Message ($NuGetOutput | Out-String) Pop-Location } @@ -199,7 +194,7 @@ if (Test-Path $ADDINS_PACKAGES_CONFIG) { Throw "An error occurred while restoring NuGet addins." } - Write-Verbose -Message ($NuGetOutput | out-string) + Write-Verbose -Message ($NuGetOutput | Out-String) Pop-Location } @@ -216,7 +211,7 @@ if (Test-Path $MODULES_PACKAGES_CONFIG) { Throw "An error occurred while restoring NuGet modules." } - Write-Verbose -Message ($NuGetOutput | out-string) + Write-Verbose -Message ($NuGetOutput | Out-String) Pop-Location } @@ -230,19 +225,28 @@ if (!(Test-Path $CAKE_EXE)) { # Build Cake arguments $cakeArguments = @("$Script"); -if ($Target) { $cakeArguments += "-target=$Target" } -if ($Configuration) { $cakeArguments += "-configuration=$Configuration" } -if ($Verbosity) { $cakeArguments += "-verbosity=$Verbosity" } -if ($ShowDescription) { $cakeArguments += "-showdescription" } -if ($DryRun) { $cakeArguments += "-dryrun" } +if ($Target) { + $cakeArguments += "-target=$Target" +} +if ($Configuration) { + $cakeArguments += "-configuration=$Configuration" +} +if ($Verbosity) { + $cakeArguments += "-verbosity=$Verbosity" +} +if ($ShowDescription) { + $cakeArguments += "-showdescription" +} +if ($DryRun) { + $cakeArguments += "-dryrun" +} $cakeArguments += $ScriptArgs # Start Cake Write-Host "Running build script..." & "$CAKE_EXE" ./recipe.cake --bootstrap -if ($LASTEXITCODE -eq 0) -{ +if ($LASTEXITCODE -eq 0) { & "$CAKE_EXE" $cakeArguments } diff --git a/docker/Install-ChocolateyInContainer.ps1 b/docker/Install-ChocolateyInContainer.ps1 index 35e5505250..0af8ce94b4 100644 --- a/docker/Install-ChocolateyInContainer.ps1 +++ b/docker/Install-ChocolateyInContainer.ps1 @@ -1,93 +1,107 @@ $nupkgDir = 'C:\choco-nupkg' -$7zPath = Join-Path $nupkgDir 'tools\7z.exe' +$7zPath = Join-Path $nupkgDir 'tools\7z.exe' function Install-LocalChocolateyPackage { -param ( - [string]$chocolateyPackageFilePath = '', - [string]$sevenZipPath = '' -) - - if ($chocolateyPackageFilePath -eq $null -or $chocolateyPackageFilePath -eq '') { - throw "You must specify a local package to run the local install." - } - - if (!(Test-Path($chocolateyPackageFilePath))) { - throw "No file exists at $chocolateyPackageFilePath" - } - - if ($sevenZipPath -eq $null -or $sevenZipPath -eq '') { - throw "You must specify a path to 7zip" - } - - if (!(Test-Path($sevenZipPath))) { - throw "No file exists at 7zipPath" - } - - if ($env:TEMP -eq $null) { - $env:TEMP = Join-Path $env:SystemDrive 'temp' - } - $chocoTempDir = Join-Path $env:TEMP "chocolatey" - $tempDir = Join-Path $chocoTempDir "chocoInstall" - if (![System.IO.Directory]::Exists($tempDir)) {[System.IO.Directory]::CreateDirectory($tempDir)} - $file = Join-Path $tempDir "chocolatey.zip" - Copy-Item $chocolateyPackageFilePath $file -Force - - # unzip the package - Write-Output "Extracting $file to $tempDir..." - $params = 'x -o"{0}" -bd -y "{1}"' -f $tempDir, $file - # use more robust Process as compared to Start-Process -Wait (which doesn't - # wait for the process to finish in PowerShell v3) - $process = New-Object System.Diagnostics.Process - - try { - $process.StartInfo = New-Object System.Diagnostics.ProcessStartInfo -ArgumentList $sevenZipPath, $params - $process.StartInfo.RedirectStandardOutput = $true - $process.StartInfo.UseShellExecute = $false - $process.StartInfo.WindowStyle = [System.Diagnostics.ProcessWindowStyle]::Hidden - - $null = $process.Start() - $process.BeginOutputReadLine() - $process.WaitForExit() - - $exitCode = $process.ExitCode - } - finally { - $process.Dispose() - } + param ( + [string]$chocolateyPackageFilePath = '', + [string]$sevenZipPath = '' + ) + + if ($chocolateyPackageFilePath -eq $null -or $chocolateyPackageFilePath -eq '') { + throw "You must specify a local package to run the local install." + } + + if (!(Test-Path($chocolateyPackageFilePath))) { + throw "No file exists at $chocolateyPackageFilePath" + } + + if ($sevenZipPath -eq $null -or $sevenZipPath -eq '') { + throw "You must specify a path to 7zip" + } + + if (!(Test-Path($sevenZipPath))) { + throw "No file exists at 7zipPath" + } + + if ($env:TEMP -eq $null) { + $env:TEMP = Join-Path $env:SystemDrive 'temp' + } + $chocoTempDir = Join-Path $env:TEMP "chocolatey" + $tempDir = Join-Path $chocoTempDir "chocoInstall" + if (![System.IO.Directory]::Exists($tempDir)) { + [System.IO.Directory]::CreateDirectory($tempDir) + } + $file = Join-Path $tempDir "chocolatey.zip" + Copy-Item $chocolateyPackageFilePath $file -Force + + # unzip the package + Write-Output "Extracting $file to $tempDir..." + $params = 'x -o"{0}" -bd -y "{1}"' -f $tempDir, $file + # use more robust Process as compared to Start-Process -Wait (which doesn't + # wait for the process to finish in PowerShell v3) + $process = New-Object System.Diagnostics.Process + + try { + $process.StartInfo = New-Object System.Diagnostics.ProcessStartInfo -ArgumentList $sevenZipPath, $params + $process.StartInfo.RedirectStandardOutput = $true + $process.StartInfo.UseShellExecute = $false + $process.StartInfo.WindowStyle = [System.Diagnostics.ProcessWindowStyle]::Hidden + + $null = $process.Start() + $process.BeginOutputReadLine() + $process.WaitForExit() + + $exitCode = $process.ExitCode + } + finally { + $process.Dispose() + } $errorMessage = "Unable to unzip package using 7zip. Error:" if ($exitCode -ne 0) { - $errorDetails = switch ($exitCode) { - 1 { "Some files could not be extracted" } - 2 { "7-Zip encountered a fatal error while extracting the files" } - 7 { "7-Zip command line error" } - 8 { "7-Zip out of memory" } - 255 { "Extraction cancelled by the user" } - default { "7-Zip signalled an unknown error (code $exitCode)" } + $errorDetails = switch ($exitCode) { + 1 { + "Some files could not be extracted" + } + 2 { + "7-Zip encountered a fatal error while extracting the files" + } + 7 { + "7-Zip command line error" + } + 8 { + "7-Zip out of memory" + } + 255 { + "Extraction cancelled by the user" + } + default { + "7-Zip signalled an unknown error (code $exitCode)" + } + } + + throw ($errorMessage, $errorDetails -join [Environment]::NewLine) } - throw ($errorMessage, $errorDetails -join [Environment]::NewLine) - } + # Call chocolatey install + Write-Output "Installing chocolatey on this machine" + $toolsFolder = Join-Path $tempDir "tools" + $chocoInstallPS1 = Join-Path $toolsFolder "chocolateyInstall.ps1" - # Call chocolatey install - Write-Output "Installing chocolatey on this machine" - $toolsFolder = Join-Path $tempDir "tools" - $chocoInstallPS1 = Join-Path $toolsFolder "chocolateyInstall.ps1" + & $chocoInstallPS1 - & $chocoInstallPS1 - - Write-Output 'Ensuring chocolatey commands are on the path' - $chocoInstallVariableName = "ChocolateyInstall" - $chocoPath = [Environment]::GetEnvironmentVariable($chocoInstallVariableName) - if ($chocoPath -eq $null -or $chocoPath -eq '') { - $chocoPath = 'C:\ProgramData\Chocolatey' - } + Write-Output 'Ensuring chocolatey commands are on the path' + $chocoInstallVariableName = "ChocolateyInstall" + $chocoPath = [Environment]::GetEnvironmentVariable($chocoInstallVariableName) + if ($chocoPath -eq $null -or $chocoPath -eq '') { + $chocoPath = 'C:\ProgramData\Chocolatey' + } - $chocoExePath = Join-Path $chocoPath 'bin' + $chocoExePath = Join-Path $chocoPath 'bin' - if ($($env:Path).ToLower().Contains($($chocoExePath).ToLower()) -eq $false) { - $env:Path = [Environment]::GetEnvironmentVariable('Path',[System.EnvironmentVariableTarget]::Machine); - } + if ($($env:Path).ToLower().Contains($($chocoExePath).ToLower()) -eq $false) { + $env:Path = [Environment]::GetEnvironmentVariable('Path', [System.EnvironmentVariableTarget]::Machine); + } } If (-not (Test-Path $nupkgDir)) { @@ -99,11 +113,11 @@ If (-not (Test-Path $7zPath)) { } -$nupkgPath = Get-Childitem -Path $nupkgDir | - ` Where-Object { $_.name -match "chocolatey.\d.*nupkg" } | - ` Select-Object -First 1 -ExpandProperty fullname +$nupkgPath = Get-ChildItem -Path $nupkgDir | + Where-Object { $_.name -match "chocolatey.\d.*nupkg" } | + Select-Object -First 1 -ExpandProperty fullname + - Write-Host "Installing Chocolatey from $nupkgPath" Install-LocalChocolateyPackage -chocolateyPackageFilePath $nupkgPath -sevenZipPath $7zPath diff --git a/formatting-settings.psd1 b/formatting-settings.psd1 new file mode 100644 index 0000000000..2f23cd8b34 --- /dev/null +++ b/formatting-settings.psd1 @@ -0,0 +1,71 @@ +@{ + IncludeRules = @( + 'PSUseBOMForUnicodeEncodedFile', + 'PSMisleadingBacktick', + 'PSAvoidUsingCmdletAliases', + 'PSAvoidTrailingWhitespace', + 'PSAvoidSemicolonsAsLineTerminators', + 'PSUseCorrectCasing', + 'PSPlaceOpenBrace', + 'PSPlaceCloseBrace', + 'PSAlignAssignmentStatement', + 'PSUseConsistentWhitespace', + 'PSUseConsistentIndentation' + ) + + Rules = @{ + + <# + PSAvoidUsingCmdletAliases = @{ + 'allowlist' = @('') + }#> + + PSAvoidSemicolonsAsLineTerminators = @{ + Enable = $true + } + + + PSUseCorrectCasing = @{ + Enable = $true + } + + PSPlaceOpenBrace = @{ + Enable = $true + OnSameLine = $true + NewLineAfter = $true + IgnoreOneLineBlock = $false + } + + PSPlaceCloseBrace = @{ + Enable = $true + NewLineAfter = $true + IgnoreOneLineBlock = $false + NoEmptyLineBefore = $true + } + + PSAlignAssignmentStatement = @{ + Enable = $true + CheckHashtable = $true + } + + PSUseConsistentIndentation = @{ + Enable = $true + Kind = 'space' + PipelineIndentation = 'IncreaseIndentationForFirstPipeline' + IndentationSize = 4 + } + + PSUseConsistentWhitespace = @{ + Enable = $true + CheckInnerBrace = $true + CheckOpenBrace = $true + CheckOpenParen = $true + CheckOperator = $true + CheckPipe = $true + CheckPipeForRedundantWhitespace = $false + CheckSeparator = $true + CheckParameter = $false + IgnoreAssignmentOperatorInsideHashTable = $true + } + } +} \ No newline at end of file diff --git a/nuspec/chocolatey/chocolatey/tools/chocolateyInstall.ps1 b/nuspec/chocolatey/chocolatey/tools/chocolateyInstall.ps1 index d7033cc01f..18bf36aad0 100644 --- a/nuspec/chocolatey/chocolatey/tools/chocolateyInstall.ps1 +++ b/nuspec/chocolatey/chocolatey/tools/chocolateyInstall.ps1 @@ -19,7 +19,8 @@ if ($null -ne $licensedAssembly) { $borderWidth = 70 try { $borderWidth = [System.Console]::BufferWidth - 10 - } catch { + } + catch { # Do nothing. This means we're in a non-interactive environment without a console attached. } @@ -62,14 +63,14 @@ $messageBorder $modules = Get-ChildItem $toolsPath -Filter *.psm1 $modules | ForEach-Object { - $psm1File = $_.FullName - $moduleName = [System.IO.Path]::GetFileNameWithoutExtension($psm1File) + $psm1File = $_.FullName + $moduleName = [System.IO.Path]::GetFileNameWithoutExtension($psm1File) - if (Get-Module $moduleName) { + if (Get-Module $moduleName) { Remove-Module $moduleName -ErrorAction SilentlyContinue } - Import-Module -Name $psm1File + Import-Module -Name $psm1File } Initialize-Chocolatey diff --git a/nuspec/chocolatey/chocolatey/tools/chocolateysetup.psm1 b/nuspec/chocolatey/chocolatey/tools/chocolateysetup.psm1 index 59a0c3caba..d02c02bbe9 100644 --- a/nuspec/chocolatey/chocolatey/tools/chocolateysetup.psm1 +++ b/nuspec/chocolatey/chocolatey/tools/chocolateysetup.psm1 @@ -1,4 +1,4 @@ -$thisScriptFolder = (Split-Path -parent $MyInvocation.MyCommand.Definition) +$thisScriptFolder = (Split-Path -Parent $MyInvocation.MyCommand.Definition) $chocoInstallVariableName = "ChocolateyInstall" $sysDrive = $env:SystemDrive $tempDir = $env:TEMP @@ -7,95 +7,97 @@ $defaultChocolateyPathOld = "$sysDrive\Chocolatey" $originalForegroundColor = $host.ui.RawUI.ForegroundColor function Write-ChocolateyWarning { -param ( - [string]$message = '' -) - - try { - Write-Host "WARNING: $message" -ForegroundColor "Yellow" -ErrorAction "Stop" - } catch { - Write-Output "WARNING: $message" - } + param ( + [string]$message = '' + ) + + try { + Write-Host "WARNING: $message" -ForegroundColor "Yellow" -ErrorAction "Stop" + } + catch { + Write-Output "WARNING: $message" + } } function Write-ChocolateyError { -param ( - [string]$message = '' -) - - try { - Write-Host "ERROR: $message" -ForegroundColor "Red" -ErrorAction "Stop" - } catch { - Write-Output "ERROR: $message" - } + param ( + [string]$message = '' + ) + + try { + Write-Host "ERROR: $message" -ForegroundColor "Red" -ErrorAction "Stop" + } + catch { + Write-Output "ERROR: $message" + } } function Remove-ShimWithAuthenticodeSignature { - param ( - [string] $filePath - ) - if (!(Test-Path $filePath)) { - return - } - - $signature = Get-AuthenticodeSignature $filePath -ErrorAction SilentlyContinue - - if (!$signature -or !$signature.SignerCertificate) { - Write-ChocolateyWarning "Shim found in $filePath, but was not signed. Ignoring removal..." - return - } - - $possibleSignatures = @( - 'RealDimensions Software, LLC' - 'Chocolatey Software, Inc\.' - ) - - $possibleSignatures | ForEach-Object { - if ($signature.SignerCertificate.Subject -match "$_") { - Write-Output "Removing shim $filePath" - $null = Remove-Item "$filePath" - - if (Test-Path "$filePath.ignore") { - $null = Remove-Item "$filePath.ignore" - } - - if (Test-Path "$filePath.old") { - $null = Remove-Item "$filePath.old" - } - } - } - - # This means the file was found, however did not get removed as it contained a authenticode signature that - # is not ours. - if (Test-Path $filePath) { - Write-ChocolateyWarning "Shim found in $filePath, but did not match our signature. Ignoring removal..." - return - } -} + param ( + [string] $filePath + ) + if (!(Test-Path $filePath)) { + return + } -function Remove-UnsupportedShimFiles { - param([string[]]$Paths) + $signature = Get-AuthenticodeSignature $filePath -ErrorAction SilentlyContinue + + if (!$signature -or !$signature.SignerCertificate) { + Write-ChocolateyWarning "Shim found in $filePath, but was not signed. Ignoring removal..." + return + } + + $possibleSignatures = @( + 'RealDimensions Software, LLC' + 'Chocolatey Software, Inc\.' + ) - $shims = @("cpack.exe", "cver.exe") + $possibleSignatures | ForEach-Object { + if ($signature.SignerCertificate.Subject -match "$_") { + Write-Output "Removing shim $filePath" + $null = Remove-Item "$filePath" - $Paths | ForEach-Object { - $path = $_ - $shims | ForEach-Object { Join-Path $path $_ } | Where-Object { Test-Path $_ } | ForEach-Object { - $shimPath = $_ - Write-Debug "Removing shim from '$shimPath'." + if (Test-Path "$filePath.ignore") { + $null = Remove-Item "$filePath.ignore" + } - try { - Remove-ShimWithAuthenticodeSignature -filePath $shimPath - } - catch { - Write-ChocolateyWarning "Unable to remove '$shimPath'. Please remove the file manually." - } + if (Test-Path "$filePath.old") { + $null = Remove-Item "$filePath.old" + } + } + } + + # This means the file was found, however did not get removed as it contained a authenticode signature that + # is not ours. + if (Test-Path $filePath) { + Write-ChocolateyWarning "Shim found in $filePath, but did not match our signature. Ignoring removal..." + return + } +} + +function Remove-UnsupportedShimFiles { + param([string[]]$Paths) + + $shims = @("cpack.exe", "cver.exe") + + $Paths | ForEach-Object { + $path = $_ + $shims | ForEach-Object { Join-Path $path $_ } | Where-Object { Test-Path $_ } | ForEach-Object { + $shimPath = $_ + Write-Debug "Removing shim from '$shimPath'." + + try { + Remove-ShimWithAuthenticodeSignature -filePath $shimPath + } + catch { + Write-ChocolateyWarning "Unable to remove '$shimPath'. Please remove the file manually." + } + } } - } } function Initialize-Chocolatey { -<# + <# .DESCRIPTION This will initialize the Chocolatey tool by a) setting up the "chocolateyPath" (the location where all chocolatey nuget packages will be installed) @@ -116,47 +118,49 @@ function Initialize-Chocolatey { Installs chocolatey into the custom directory D:\ChocolateyInstalledNuGets\ #> -param( - [Parameter(Mandatory=$false)][string]$chocolateyPath = '' -) - Write-Debug "Initialize-Chocolatey" + param( + [Parameter(Mandatory = $false)][string]$chocolateyPath = '' + ) + Write-Debug "Initialize-Chocolatey" - $installModule = Join-Path $thisScriptFolder 'chocolateyInstall\helpers\chocolateyInstaller.psm1' - Import-Module $installModule -Force + $installModule = Join-Path $thisScriptFolder 'chocolateyInstall\helpers\chocolateyInstaller.psm1' + Import-Module $installModule -Force Install-DotNet48IfMissing - if ($chocolateyPath -eq '') { - $programData = [Environment]::GetFolderPath("CommonApplicationData") - $chocolateyPath = Join-Path "$programData" 'chocolatey' - } - - # variable to allow insecure directory: - $allowInsecureRootInstall = $false - if ($env:ChocolateyAllowInsecureRootDirectory -eq 'true') { $allowInsecureRootInstall = $true } - - # if we have an already environment variable path, use it. - $alreadyInitializedNugetPath = Get-ChocolateyInstallFolder - if ($alreadyInitializedNugetPath -and $alreadyInitializedNugetPath -ne $chocolateyPath -and ($allowInsecureRootInstall -or $alreadyInitializedNugetPath -ne $defaultChocolateyPathOld)){ - $chocolateyPath = $alreadyInitializedNugetPath - } - else { - Set-ChocolateyInstallFolder $chocolateyPath - } - Create-DirectoryIfNotExists $chocolateyPath - Ensure-Permissions $chocolateyPath - - #set up variables to add - $chocolateyExePath = Join-Path $chocolateyPath 'bin' - $chocolateyLibPath = Join-Path $chocolateyPath 'lib' - - if ($tempDir -eq $null) { - $tempDir = Join-Path $chocolateyPath 'temp' - Create-DirectoryIfNotExists $tempDir - } - - $yourPkgPath = [System.IO.Path]::Combine($chocolateyLibPath,"yourPackageName") -@" + if ($chocolateyPath -eq '') { + $programData = [Environment]::GetFolderPath("CommonApplicationData") + $chocolateyPath = Join-Path "$programData" 'chocolatey' + } + + # variable to allow insecure directory: + $allowInsecureRootInstall = $false + if ($env:ChocolateyAllowInsecureRootDirectory -eq 'true') { + $allowInsecureRootInstall = $true + } + + # if we have an already environment variable path, use it. + $alreadyInitializedNugetPath = Get-ChocolateyInstallFolder + if ($alreadyInitializedNugetPath -and $alreadyInitializedNugetPath -ne $chocolateyPath -and ($allowInsecureRootInstall -or $alreadyInitializedNugetPath -ne $defaultChocolateyPathOld)) { + $chocolateyPath = $alreadyInitializedNugetPath + } + else { + Set-ChocolateyInstallFolder $chocolateyPath + } + Create-DirectoryIfNotExists $chocolateyPath + Ensure-Permissions $chocolateyPath + + #set up variables to add + $chocolateyExePath = Join-Path $chocolateyPath 'bin' + $chocolateyLibPath = Join-Path $chocolateyPath 'lib' + + if ($tempDir -eq $null) { + $tempDir = Join-Path $chocolateyPath 'temp' + Create-DirectoryIfNotExists $tempDir + } + + $yourPkgPath = [System.IO.Path]::Combine($chocolateyLibPath, "yourPackageName") + @" We are setting up the Chocolatey package repository. The packages themselves go to `'$chocolateyLibPath`' (i.e. $yourPkgPath). @@ -167,534 +171,562 @@ Creating Chocolatey folders if they do not already exist. "@ | Write-Output - Write-ChocolateyWarning "You can safely ignore errors related to missing log files when `n upgrading from a version of Chocolatey less than 0.9.9. `n 'Batch file could not be found' is also safe to ignore. `n 'The system cannot find the file specified' - also safe." + Write-ChocolateyWarning "You can safely ignore errors related to missing log files when `n upgrading from a version of Chocolatey less than 0.9.9. `n 'Batch file could not be found' is also safe to ignore. `n 'The system cannot find the file specified' - also safe." - #create the base structure if it doesn't exist - Create-DirectoryIfNotExists $chocolateyExePath - Create-DirectoryIfNotExists $chocolateyLibPath + #create the base structure if it doesn't exist + Create-DirectoryIfNotExists $chocolateyExePath + Create-DirectoryIfNotExists $chocolateyLibPath - $possibleShimPaths = @( - Join-Path "$chocolateyPath" "redirects" - Join-Path "$thisScriptFolder" "chocolateyInstall\redirects" - ) - Remove-UnsupportedShimFiles -Paths $possibleShimPaths + $possibleShimPaths = @( + Join-Path "$chocolateyPath" "redirects" + Join-Path "$thisScriptFolder" "chocolateyInstall\redirects" + ) + Remove-UnsupportedShimFiles -Paths $possibleShimPaths - Install-ChocolateyFiles $chocolateyPath - Ensure-ChocolateyLibFiles $chocolateyLibPath + Install-ChocolateyFiles $chocolateyPath + Ensure-ChocolateyLibFiles $chocolateyLibPath - Install-ChocolateyBinFiles $chocolateyPath $chocolateyExePath + Install-ChocolateyBinFiles $chocolateyPath $chocolateyExePath - $chocolateyExePathVariable = $chocolateyExePath.ToLower().Replace($chocolateyPath.ToLower(), "%DIR%..\").Replace("\\","\") - Initialize-ChocolateyPath $chocolateyExePath $chocolateyExePathVariable - Process-ChocolateyBinFiles $chocolateyExePath $chocolateyExePathVariable + $chocolateyExePathVariable = $chocolateyExePath.ToLower().Replace($chocolateyPath.ToLower(), "%DIR%..\").Replace("\\", "\") + Initialize-ChocolateyPath $chocolateyExePath $chocolateyExePathVariable + Process-ChocolateyBinFiles $chocolateyExePath $chocolateyExePathVariable - $realModule = Join-Path $chocolateyPath "helpers\chocolateyInstaller.psm1" - Import-Module "$realModule" -Force + $realModule = Join-Path $chocolateyPath "helpers\chocolateyInstaller.psm1" + Import-Module "$realModule" -Force - if (-not $allowInsecureRootInstall -and (Test-Path($defaultChocolateyPathOld))) { - Upgrade-OldChocolateyInstall $defaultChocolateyPathOld $chocolateyPath - Install-ChocolateyBinFiles $chocolateyPath $chocolateyExePath - } + if (-not $allowInsecureRootInstall -and (Test-Path($defaultChocolateyPathOld))) { + Upgrade-OldChocolateyInstall $defaultChocolateyPathOld $chocolateyPath + Install-ChocolateyBinFiles $chocolateyPath $chocolateyExePath + } - Add-ChocolateyProfile - Invoke-Chocolatey-Initial - if ($env:ChocolateyExitCode -eq $null -or $env:ChocolateyExitCode -eq '') { - $env:ChocolateyExitCode = 0 - } + Add-ChocolateyProfile + Invoke-Chocolatey-Initial + if ($env:ChocolateyExitCode -eq $null -or $env:ChocolateyExitCode -eq '') { + $env:ChocolateyExitCode = 0 + } -@" + @" Chocolatey (choco.exe) is now ready. You can call choco from anywhere, command line or powershell by typing choco. Run choco /? for a list of functions. You may need to shut down and restart powershell and/or consoles first prior to using choco. -"@ | write-Output +"@ | Write-Output - if (-not $allowInsecureRootInstall) { - Remove-OldChocolateyInstall $defaultChocolateyPathOld - } + if (-not $allowInsecureRootInstall) { + Remove-OldChocolateyInstall $defaultChocolateyPathOld + } - Remove-UnsupportedShimFiles -Paths $chocolateyExePath + Remove-UnsupportedShimFiles -Paths $chocolateyExePath } function Set-ChocolateyInstallFolder { -param( - [string]$folder -) - Write-Debug "Set-ChocolateyInstallFolder" - - $environmentTarget = [System.EnvironmentVariableTarget]::User - # removing old variable - Install-ChocolateyEnvironmentVariable -variableName "$chocoInstallVariableName" -variableValue $null -variableType $environmentTarget - if (Test-ProcessAdminRights) { - Write-Debug "Administrator installing so using Machine environment variable target instead of User." - $environmentTarget = [System.EnvironmentVariableTarget]::Machine + param( + [string]$folder + ) + Write-Debug "Set-ChocolateyInstallFolder" + + $environmentTarget = [System.EnvironmentVariableTarget]::User # removing old variable Install-ChocolateyEnvironmentVariable -variableName "$chocoInstallVariableName" -variableValue $null -variableType $environmentTarget - } else { - Write-ChocolateyWarning "Setting ChocolateyInstall Environment Variable on USER and not SYSTEM variables.`n This is due to either non-administrator install OR the process you are running is not being run as an Administrator." - } + if (Test-ProcessAdminRights) { + Write-Debug "Administrator installing so using Machine environment variable target instead of User." + $environmentTarget = [System.EnvironmentVariableTarget]::Machine + # removing old variable + Install-ChocolateyEnvironmentVariable -variableName "$chocoInstallVariableName" -variableValue $null -variableType $environmentTarget + } + else { + Write-ChocolateyWarning "Setting ChocolateyInstall Environment Variable on USER and not SYSTEM variables.`n This is due to either non-administrator install OR the process you are running is not being run as an Administrator." + } - Write-Output "Creating $chocoInstallVariableName as an environment variable (targeting `'$environmentTarget`') `n Setting $chocoInstallVariableName to `'$folder`'" - Write-ChocolateyWarning "It's very likely you will need to close and reopen your shell `n before you can use choco." - Install-ChocolateyEnvironmentVariable -variableName "$chocoInstallVariableName" -variableValue "$folder" -variableType $environmentTarget + Write-Output "Creating $chocoInstallVariableName as an environment variable (targeting `'$environmentTarget`') `n Setting $chocoInstallVariableName to `'$folder`'" + Write-ChocolateyWarning "It's very likely you will need to close and reopen your shell `n before you can use choco." + Install-ChocolateyEnvironmentVariable -variableName "$chocoInstallVariableName" -variableValue "$folder" -variableType $environmentTarget } -function Get-ChocolateyInstallFolder(){ - Write-Debug "Get-ChocolateyInstallFolder" - [Environment]::GetEnvironmentVariable($chocoInstallVariableName) +function Get-ChocolateyInstallFolder() { + Write-Debug "Get-ChocolateyInstallFolder" + [Environment]::GetEnvironmentVariable($chocoInstallVariableName) } -function Create-DirectoryIfNotExists($folderName){ - Write-Debug "Create-DirectoryIfNotExists" - if (![System.IO.Directory]::Exists($folderName)) { [System.IO.Directory]::CreateDirectory($folderName) | Out-Null } +function Create-DirectoryIfNotExists($folderName) { + Write-Debug "Create-DirectoryIfNotExists" + if (![System.IO.Directory]::Exists($folderName)) { + [System.IO.Directory]::CreateDirectory($folderName) | Out-Null + } } function Get-LocalizedWellKnownPrincipalName { -param ( - [Parameter(Mandatory = $true)] - [Security.Principal.WellKnownSidType] $WellKnownSidType -) - $sid = New-Object -TypeName 'System.Security.Principal.SecurityIdentifier' -ArgumentList @($WellKnownSidType, $null) - $account = $sid.Translate([Security.Principal.NTAccount]) - - return $account.Value + param ( + [Parameter(Mandatory = $true)] + [Security.Principal.WellKnownSidType] $WellKnownSidType + ) + $sid = New-Object -TypeName 'System.Security.Principal.SecurityIdentifier' -ArgumentList @($WellKnownSidType, $null) + $account = $sid.Translate([Security.Principal.NTAccount]) + + return $account.Value } function Ensure-Permissions { -param( - [string]$folder -) - Write-Debug "Ensure-Permissions" - - $defaultInstallPath = "$env:SystemDrive\ProgramData\chocolatey" - try { - $defaultInstallPath = Join-Path ([Environment]::GetFolderPath("CommonApplicationData")) 'chocolatey' - } catch { - # keep first setting - } - - if ($folder.ToLower() -ne $defaultInstallPath.ToLower()) { - Write-ChocolateyWarning "Installation folder is not the default. Not changing permissions. Please ensure your installation is secure." - return - } - - # Everything from here on out applies to the default installation folder - - if (!(Test-ProcessAdminRights)) { - throw "Installation of Chocolatey to default folder requires Administrative permissions. Please run from elevated prompt. Please see https://chocolatey.org/install for details and alternatives if needing to install as a non-administrator." - } - - $currentEA = $ErrorActionPreference - $ErrorActionPreference = 'Stop' - try { - # get current acl - $acl = Get-Acl $folder - - Write-Debug "Removing existing permissions." - $acl.Access | ForEach-Object { $acl.RemoveAccessRuleAll($_) } - - $inheritanceFlags = ([Security.AccessControl.InheritanceFlags]::ContainerInherit -bor [Security.AccessControl.InheritanceFlags]::ObjectInherit) - $propagationFlags = [Security.AccessControl.PropagationFlags]::None - - $rightsFullControl = [Security.AccessControl.FileSystemRights]::FullControl - $rightsModify = [Security.AccessControl.FileSystemRights]::Modify - $rightsReadExecute = [Security.AccessControl.FileSystemRights]::ReadAndExecute - $rightsWrite = [Security.AccessControl.FileSystemRights]::Write - - Write-Output "Restricting write permissions to Administrators" - $builtinAdmins = Get-LocalizedWellKnownPrincipalName -WellKnownSidType ([Security.Principal.WellKnownSidType]::BuiltinAdministratorsSid) - $adminsAccessRule = New-Object System.Security.AccessControl.FileSystemAccessRule($builtinAdmins, $rightsFullControl, $inheritanceFlags, $propagationFlags, "Allow") - $acl.SetAccessRule($adminsAccessRule) - $localSystem = Get-LocalizedWellKnownPrincipalName -WellKnownSidType ([Security.Principal.WellKnownSidType]::LocalSystemSid) - $localSystemAccessRule = New-Object System.Security.AccessControl.FileSystemAccessRule($localSystem, $rightsFullControl, $inheritanceFlags, $propagationFlags, "Allow") - $acl.SetAccessRule($localSystemAccessRule) - $builtinUsers = Get-LocalizedWellKnownPrincipalName -WellKnownSidType ([Security.Principal.WellKnownSidType]::BuiltinUsersSid) - $usersAccessRule = New-Object System.Security.AccessControl.FileSystemAccessRule($builtinUsers, $rightsReadExecute, $inheritanceFlags, $propagationFlags, "Allow") - $acl.SetAccessRule($usersAccessRule) - - $allowCurrentUser = $env:ChocolateyInstallAllowCurrentUser -eq 'true' - if ($allowCurrentUser) { - # get current user - $currentUser = [Security.Principal.WindowsIdentity]::GetCurrent() - - if ($currentUser.Name -ne $localSystem) { - $userAccessRule = New-Object System.Security.AccessControl.FileSystemAccessRule($currentUser.Name, $rightsModify, $inheritanceFlags, $propagationFlags, "Allow") - Write-ChocolateyWarning 'Adding Modify permission for current user due to $env:ChocolateyInstallAllowCurrentUser. This could lead to escalation of privilege attacks. Consider not allowing this.' - $acl.SetAccessRule($userAccessRule) - } - } else { - Write-Debug 'Current user no longer set due to possible escalation of privileges - set $env:ChocolateyInstallAllowCurrentUser="true" if you require this.' - } - - Write-Debug "Set Owner to Administrators" - $builtinAdminsSid = New-Object System.Security.Principal.SecurityIdentifier([Security.Principal.WellKnownSidType]::BuiltinAdministratorsSid, $null) - $acl.SetOwner($builtinAdminsSid) - - Write-Debug "Default Installation folder - removing inheritance with no copy" - $acl.SetAccessRuleProtection($true, $false) - - # enact the changes against the actual - Set-Acl -Path $folder -AclObject $acl - - # set an explicit append permission on the logs folder - Write-Debug "Allow users to append to log files." - $logsFolder = "$folder\logs" - Create-DirectoryIfNotExists $logsFolder - $logsAcl = Get-Acl $logsFolder - $usersAppendAccessRule = New-Object System.Security.AccessControl.FileSystemAccessRule($builtinUsers, $rightsWrite, [Security.AccessControl.InheritanceFlags]::ObjectInherit, [Security.AccessControl.PropagationFlags]::InheritOnly, "Allow") - $logsAcl.SetAccessRule($usersAppendAccessRule) - $logsAcl.SetAccessRuleProtection($false, $true) - Set-Acl -Path $logsFolder -AclObject $logsAcl - } catch { - Write-ChocolateyWarning "Not able to set permissions for $folder." - } - $ErrorActionPreference = $currentEA -} + param( + [string]$folder + ) + Write-Debug "Ensure-Permissions" -function Upgrade-OldChocolateyInstall { -param( - [string]$chocolateyPathOld = "$sysDrive\Chocolatey", - [string]$chocolateyPath = "$($env:ALLUSERSPROFILE)\chocolatey" -) - - Write-Debug "Upgrade-OldChocolateyInstall" - - if (Test-Path $chocolateyPathOld) { - Write-Output "Attempting to upgrade `'$chocolateyPathOld`' to `'$chocolateyPath`'." - Write-ChocolateyWarning "Copying the contents of `'$chocolateyPathOld`' to `'$chocolateyPath`'. `n This step may fail if you have anything in this folder running or locked." - Write-Output 'If it fails, just manually copy the rest of the items out and then delete the folder.' - Write-ChocolateyWarning "!!!! ATTN: YOU WILL NEED TO CLOSE AND REOPEN YOUR SHELL !!!!" - #-ForegroundColor Magenta -BackgroundColor Black - - $chocolateyExePathOld = Join-Path $chocolateyPathOld 'bin' - 'Machine', 'User' | - ForEach-Object { - $path = Get-EnvironmentVariable -Name 'PATH' -Scope $_ - $updatedPath = [System.Text.RegularExpressions.Regex]::Replace($path,[System.Text.RegularExpressions.Regex]::Escape($chocolateyExePathOld) + '(?>;)?', '', [System.Text.RegularExpressions.RegexOptions]::IgnoreCase) - if ($updatedPath -ne $path) { - Write-Output "Updating `'$_`' PATH to reflect removal of '$chocolateyPathOld'." - try { - Set-EnvironmentVariable -Name 'Path' -Value $updatedPath -Scope $_ -ErrorAction Stop - } catch { - Write-ChocolateyWarning "Was not able to remove the old environment variable from PATH. You will need to do this manually" - } - - } - } - - Copy-Item "$chocolateyPathOld\lib\*" "$chocolateyPath\lib" -force -recurse - - $from = "$chocolateyPathOld\bin" - $to = "$chocolateyPath\bin" - # TODO: This exclusion list needs to be updated once shims are removed - $exclude = @("choco.exe", "chocolatey.exe", "cinst.exe", "clist.exe", "cpush.exe", "cuninst.exe", "cup.exe", "RefreshEnv.cmd") - Get-ChildItem -Path $from -recurse -Exclude $exclude | - ForEach-Object { - Write-Debug "Copying $_ `n to $to" - if ($_.PSIsContainer) { - Copy-Item $_ -Destination (Join-Path $to $_.Parent.FullName.Substring($from.length)) -Force -ErrorAction SilentlyContinue - } else { - $fileToMove = (Join-Path $to $_.FullName.Substring($from.length)) - try { - Copy-Item $_ -Destination $fileToMove -Exclude $exclude -Force -ErrorAction Stop - } - catch { - Write-ChocolateyWarning "Was not able to move `'$fileToMove`'. You may need to reinstall the shim" - } - } - } - } -} + $defaultInstallPath = "$env:SystemDrive\ProgramData\chocolatey" + try { + $defaultInstallPath = Join-Path ([Environment]::GetFolderPath("CommonApplicationData")) 'chocolatey' + } + catch { + # keep first setting + } -function Remove-OldChocolateyInstall { -param( - [string]$chocolateyPathOld = "$sysDrive\Chocolatey" -) - Write-Debug "Remove-OldChocolateyInstall" + if ($folder.ToLower() -ne $defaultInstallPath.ToLower()) { + Write-ChocolateyWarning "Installation folder is not the default. Not changing permissions. Please ensure your installation is secure." + return + } + + # Everything from here on out applies to the default installation folder - if (Test-Path $chocolateyPathOld) { - Write-ChocolateyWarning "This action will result in Log Errors, you can safely ignore those. `n You may need to finish removing '$chocolateyPathOld' manually." + if (!(Test-ProcessAdminRights)) { + throw "Installation of Chocolatey to default folder requires Administrative permissions. Please run from elevated prompt. Please see https://chocolatey.org/install for details and alternatives if needing to install as a non-administrator." + } + + $currentEA = $ErrorActionPreference + $ErrorActionPreference = 'Stop' try { - Get-ChildItem -Path "$chocolateyPathOld" | ForEach-Object { - if (Test-Path $_.FullName) { - Write-Debug "Removing $_ unless matches .log" - Remove-Item $_.FullName -exclude *.log -recurse -force -ErrorAction SilentlyContinue + # get current acl + $acl = Get-Acl $folder + + Write-Debug "Removing existing permissions." + $acl.Access | ForEach-Object { $acl.RemoveAccessRuleAll($_) } + + $inheritanceFlags = ([Security.AccessControl.InheritanceFlags]::ContainerInherit -bor [Security.AccessControl.InheritanceFlags]::ObjectInherit) + $propagationFlags = [Security.AccessControl.PropagationFlags]::None + + $rightsFullControl = [Security.AccessControl.FileSystemRights]::FullControl + $rightsModify = [Security.AccessControl.FileSystemRights]::Modify + $rightsReadExecute = [Security.AccessControl.FileSystemRights]::ReadAndExecute + $rightsWrite = [Security.AccessControl.FileSystemRights]::Write + + Write-Output "Restricting write permissions to Administrators" + $builtinAdmins = Get-LocalizedWellKnownPrincipalName -WellKnownSidType ([Security.Principal.WellKnownSidType]::BuiltinAdministratorsSid) + $adminsAccessRule = New-Object System.Security.AccessControl.FileSystemAccessRule($builtinAdmins, $rightsFullControl, $inheritanceFlags, $propagationFlags, "Allow") + $acl.SetAccessRule($adminsAccessRule) + $localSystem = Get-LocalizedWellKnownPrincipalName -WellKnownSidType ([Security.Principal.WellKnownSidType]::LocalSystemSid) + $localSystemAccessRule = New-Object System.Security.AccessControl.FileSystemAccessRule($localSystem, $rightsFullControl, $inheritanceFlags, $propagationFlags, "Allow") + $acl.SetAccessRule($localSystemAccessRule) + $builtinUsers = Get-LocalizedWellKnownPrincipalName -WellKnownSidType ([Security.Principal.WellKnownSidType]::BuiltinUsersSid) + $usersAccessRule = New-Object System.Security.AccessControl.FileSystemAccessRule($builtinUsers, $rightsReadExecute, $inheritanceFlags, $propagationFlags, "Allow") + $acl.SetAccessRule($usersAccessRule) + + $allowCurrentUser = $env:ChocolateyInstallAllowCurrentUser -eq 'true' + if ($allowCurrentUser) { + # get current user + $currentUser = [Security.Principal.WindowsIdentity]::GetCurrent() + + if ($currentUser.Name -ne $localSystem) { + $userAccessRule = New-Object System.Security.AccessControl.FileSystemAccessRule($currentUser.Name, $rightsModify, $inheritanceFlags, $propagationFlags, "Allow") + Write-ChocolateyWarning 'Adding Modify permission for current user due to $env:ChocolateyInstallAllowCurrentUser. This could lead to escalation of privilege attacks. Consider not allowing this.' + $acl.SetAccessRule($userAccessRule) + } + } + else { + Write-Debug 'Current user no longer set due to possible escalation of privileges - set $env:ChocolateyInstallAllowCurrentUser="true" if you require this.' } - } - Write-Output "Attempting to remove `'$chocolateyPathOld`'. This may fail if something in the folder is being used or locked." - Remove-Item "$($chocolateyPathOld)" -force -recurse -ErrorAction Stop + Write-Debug "Set Owner to Administrators" + $builtinAdminsSid = New-Object System.Security.Principal.SecurityIdentifier([Security.Principal.WellKnownSidType]::BuiltinAdministratorsSid, $null) + $acl.SetOwner($builtinAdminsSid) + + Write-Debug "Default Installation folder - removing inheritance with no copy" + $acl.SetAccessRuleProtection($true, $false) + + # enact the changes against the actual + Set-Acl -Path $folder -AclObject $acl + + # set an explicit append permission on the logs folder + Write-Debug "Allow users to append to log files." + $logsFolder = "$folder\logs" + Create-DirectoryIfNotExists $logsFolder + $logsAcl = Get-Acl $logsFolder + $usersAppendAccessRule = New-Object System.Security.AccessControl.FileSystemAccessRule($builtinUsers, $rightsWrite, [Security.AccessControl.InheritanceFlags]::ObjectInherit, [Security.AccessControl.PropagationFlags]::InheritOnly, "Allow") + $logsAcl.SetAccessRule($usersAppendAccessRule) + $logsAcl.SetAccessRuleProtection($false, $true) + Set-Acl -Path $logsFolder -AclObject $logsAcl } catch { - Write-ChocolateyWarning "Was not able to remove `'$chocolateyPathOld`'. You will need to manually remove it." + Write-ChocolateyWarning "Not able to set permissions for $folder." + } + $ErrorActionPreference = $currentEA +} + +function Upgrade-OldChocolateyInstall { + param( + [string]$chocolateyPathOld = "$sysDrive\Chocolatey", + [string]$chocolateyPath = "$($env:ALLUSERSPROFILE)\chocolatey" + ) + + Write-Debug "Upgrade-OldChocolateyInstall" + + if (Test-Path $chocolateyPathOld) { + Write-Output "Attempting to upgrade `'$chocolateyPathOld`' to `'$chocolateyPath`'." + Write-ChocolateyWarning "Copying the contents of `'$chocolateyPathOld`' to `'$chocolateyPath`'. `n This step may fail if you have anything in this folder running or locked." + Write-Output 'If it fails, just manually copy the rest of the items out and then delete the folder.' + Write-ChocolateyWarning "!!!! ATTN: YOU WILL NEED TO CLOSE AND REOPEN YOUR SHELL !!!!" + #-ForegroundColor Magenta -BackgroundColor Black + + $chocolateyExePathOld = Join-Path $chocolateyPathOld 'bin' + 'Machine', 'User' | + ForEach-Object { + $path = Get-EnvironmentVariable -Name 'PATH' -Scope $_ + $updatedPath = [System.Text.RegularExpressions.Regex]::Replace($path, [System.Text.RegularExpressions.Regex]::Escape($chocolateyExePathOld) + '(?>;)?', '', [System.Text.RegularExpressions.RegexOptions]::IgnoreCase) + if ($updatedPath -ne $path) { + Write-Output "Updating `'$_`' PATH to reflect removal of '$chocolateyPathOld'." + try { + Set-EnvironmentVariable -Name 'Path' -Value $updatedPath -Scope $_ -ErrorAction Stop + } + catch { + Write-ChocolateyWarning "Was not able to remove the old environment variable from PATH. You will need to do this manually" + } + } + } + + Copy-Item "$chocolateyPathOld\lib\*" "$chocolateyPath\lib" -Force -Recurse + + $from = "$chocolateyPathOld\bin" + $to = "$chocolateyPath\bin" + # TODO: This exclusion list needs to be updated once shims are removed + $exclude = @("choco.exe", "chocolatey.exe", "cinst.exe", "clist.exe", "cpush.exe", "cuninst.exe", "cup.exe", "RefreshEnv.cmd") + Get-ChildItem -Path $from -Recurse -Exclude $exclude | + ForEach-Object { + Write-Debug "Copying $_ `n to $to" + if ($_.PSIsContainer) { + Copy-Item $_ -Destination (Join-Path $to $_.Parent.FullName.Substring($from.length)) -Force -ErrorAction SilentlyContinue + } + else { + $fileToMove = (Join-Path $to $_.FullName.Substring($from.length)) + try { + Copy-Item $_ -Destination $fileToMove -Exclude $exclude -Force -ErrorAction Stop + } + catch { + Write-ChocolateyWarning "Was not able to move `'$fileToMove`'. You may need to reinstall the shim" + } + } + } + } +} + +function Remove-OldChocolateyInstall { + param( + [string]$chocolateyPathOld = "$sysDrive\Chocolatey" + ) + Write-Debug "Remove-OldChocolateyInstall" + + if (Test-Path $chocolateyPathOld) { + Write-ChocolateyWarning "This action will result in Log Errors, you can safely ignore those. `n You may need to finish removing '$chocolateyPathOld' manually." + try { + Get-ChildItem -Path "$chocolateyPathOld" | ForEach-Object { + if (Test-Path $_.FullName) { + Write-Debug "Removing $_ unless matches .log" + Remove-Item $_.FullName -Exclude *.log -Recurse -Force -ErrorAction SilentlyContinue + } + } + + Write-Output "Attempting to remove `'$chocolateyPathOld`'. This may fail if something in the folder is being used or locked." + Remove-Item "$($chocolateyPathOld)" -Force -Recurse -ErrorAction Stop + } + catch { + Write-ChocolateyWarning "Was not able to remove `'$chocolateyPathOld`'. You will need to manually remove it." + } } - } } function Install-ChocolateyFiles { -param( - [string]$chocolateyPath -) - Write-Debug "Install-ChocolateyFiles" - - Write-Debug "Removing install files in chocolateyInstall, helpers, redirects, and tools" - "$chocolateyPath\chocolateyInstall", "$chocolateyPath\helpers", "$chocolateyPath\redirects", "$chocolateyPath\tools" | ForEach-Object { - #Write-Debug "Checking path $_" - - if (Test-Path $_) { - Get-ChildItem -Path "$_" | ForEach-Object { - #Write-Debug "Checking child path $_ ($($_.FullName))" - if (Test-Path $_.FullName) { - Write-Debug "Removing $_ unless matches .log" - Remove-Item $_.FullName -exclude *.log -recurse -force -ErrorAction SilentlyContinue - } - } - } - } - - Write-Debug "Attempting to move choco.exe to choco.exe.old so we can place the new version here." - # rename the currently running process / it will be locked if it exists - $chocoExe = Join-Path $chocolateyPath 'choco.exe' - if (Test-Path ($chocoExe)) { - Write-Debug "Renaming '$chocoExe' to '$chocoExe.old'" - try { - Remove-Item "$chocoExe.old" -force -ErrorAction SilentlyContinue - Move-Item $chocoExe "$chocoExe.old" -force -ErrorAction SilentlyContinue + param( + [string]$chocolateyPath + ) + Write-Debug "Install-ChocolateyFiles" + + Write-Debug "Removing install files in chocolateyInstall, helpers, redirects, and tools" + "$chocolateyPath\chocolateyInstall", "$chocolateyPath\helpers", "$chocolateyPath\redirects", "$chocolateyPath\tools" | ForEach-Object { + #Write-Debug "Checking path $_" + + if (Test-Path $_) { + Get-ChildItem -Path "$_" | ForEach-Object { + #Write-Debug "Checking child path $_ ($($_.FullName))" + if (Test-Path $_.FullName) { + Write-Debug "Removing $_ unless matches .log" + Remove-Item $_.FullName -Exclude *.log -Recurse -Force -ErrorAction SilentlyContinue + } + } + } } - catch { - Write-ChocolateyWarning "Was not able to rename `'$chocoExe`' to `'$chocoExe.old`'." + + Write-Debug "Attempting to move choco.exe to choco.exe.old so we can place the new version here." + # rename the currently running process / it will be locked if it exists + $chocoExe = Join-Path $chocolateyPath 'choco.exe' + if (Test-Path ($chocoExe)) { + Write-Debug "Renaming '$chocoExe' to '$chocoExe.old'" + try { + Remove-Item "$chocoExe.old" -Force -ErrorAction SilentlyContinue + Move-Item $chocoExe "$chocoExe.old" -Force -ErrorAction SilentlyContinue + } + catch { + Write-ChocolateyWarning "Was not able to rename `'$chocoExe`' to `'$chocoExe.old`'." + } } - } - # remove pdb file if it is found - $chocoPdb = Join-Path $chocolateyPath 'choco.pdb' - if (Test-Path ($chocoPdb)) { - Remove-Item "$chocoPdb" -Force -ErrorAction SilentlyContinue - } + # remove pdb file if it is found + $chocoPdb = Join-Path $chocolateyPath 'choco.pdb' + if (Test-Path ($chocoPdb)) { + Remove-Item "$chocoPdb" -Force -ErrorAction SilentlyContinue + } - Write-Debug "Unpacking files required for Chocolatey." - $chocoInstallFolder = Join-Path $thisScriptFolder "chocolateyInstall" - $chocoExe = Join-Path $chocoInstallFolder 'choco.exe' - $chocoExeDest = Join-Path $chocolateyPath 'choco.exe' - Copy-Item $chocoExe $chocoExeDest -force + Write-Debug "Unpacking files required for Chocolatey." + $chocoInstallFolder = Join-Path $thisScriptFolder "chocolateyInstall" + $chocoExe = Join-Path $chocoInstallFolder 'choco.exe' + $chocoExeDest = Join-Path $chocolateyPath 'choco.exe' + Copy-Item $chocoExe $chocoExeDest -Force - Write-Debug "Copying the contents of `'$chocoInstallFolder`' to `'$chocolateyPath`'." - Copy-Item $chocoInstallFolder\* $chocolateyPath -Recurse -Force + Write-Debug "Copying the contents of `'$chocoInstallFolder`' to `'$chocolateyPath`'." + Copy-Item $chocoInstallFolder\* $chocolateyPath -Recurse -Force } function Ensure-ChocolateyLibFiles { -param( - [string]$chocolateyLibPath -) - Write-Debug "Ensure-ChocolateyLibFiles" - $chocoPkgDirectory = Join-Path $chocolateyLibPath 'chocolatey' + param( + [string]$chocolateyLibPath + ) + Write-Debug "Ensure-ChocolateyLibFiles" + $chocoPkgDirectory = Join-Path $chocolateyLibPath 'chocolatey' - Create-DirectoryIfNotExists $chocoPkgDirectory + Create-DirectoryIfNotExists $chocoPkgDirectory - if (!(Test-Path("$chocoPkgDirectory\chocolatey.nupkg"))) { - Write-Output "chocolatey.nupkg file not installed in lib.`n Attempting to locate it from bootstrapper." - $chocoZipFile = Join-Path $tempDir "chocolatey\chocoInstall\chocolatey.zip" + if (!(Test-Path("$chocoPkgDirectory\chocolatey.nupkg"))) { + Write-Output "chocolatey.nupkg file not installed in lib.`n Attempting to locate it from bootstrapper." + $chocoZipFile = Join-Path $tempDir "chocolatey\chocoInstall\chocolatey.zip" - Write-Debug "First the zip file at '$chocoZipFile'." - Write-Debug "Then from a neighboring chocolatey.*nupkg file '$thisScriptFolder/../../'." + Write-Debug "First the zip file at '$chocoZipFile'." + Write-Debug "Then from a neighboring chocolatey.*nupkg file '$thisScriptFolder/../../'." - if (Test-Path("$chocoZipFile")) { - Write-Debug "Copying '$chocoZipFile' to '$chocoPkgDirectory\chocolatey.nupkg'." - Copy-Item "$chocoZipFile" "$chocoPkgDirectory\chocolatey.nupkg" -Force -ErrorAction SilentlyContinue - } + if (Test-Path("$chocoZipFile")) { + Write-Debug "Copying '$chocoZipFile' to '$chocoPkgDirectory\chocolatey.nupkg'." + Copy-Item "$chocoZipFile" "$chocoPkgDirectory\chocolatey.nupkg" -Force -ErrorAction SilentlyContinue + } - if (!(Test-Path("$chocoPkgDirectory\chocolatey.nupkg"))) { - $chocoPkg = Get-ChildItem "$thisScriptFolder/../../" | - Where-Object {$_.name -match "^chocolatey.*nupkg" } | - Sort-Object name -Descending | - Select-Object -First 1 - if ($chocoPkg -ne '') { $chocoPkg = $chocoPkg.FullName } - "$chocoZipFile", "$chocoPkg" | ForEach-Object { - if ($_ -ne $null -and $_ -ne '') { - if (Test-Path $_) { - Write-Debug "Copying '$_' to '$chocoPkgDirectory\chocolatey.nupkg'." - Copy-Item $_ "$chocoPkgDirectory\chocolatey.nupkg" -Force -ErrorAction SilentlyContinue - } - } - } - } - } + if (!(Test-Path("$chocoPkgDirectory\chocolatey.nupkg"))) { + $chocoPkg = Get-ChildItem "$thisScriptFolder/../../" | + Where-Object { $_.name -match "^chocolatey.*nupkg" } | + Sort-Object name -Descending | + Select-Object -First 1 + if ($chocoPkg -ne '') { + $chocoPkg = $chocoPkg.FullName + } + "$chocoZipFile", "$chocoPkg" | ForEach-Object { + if ($_ -ne $null -and $_ -ne '') { + if (Test-Path $_) { + Write-Debug "Copying '$_' to '$chocoPkgDirectory\chocolatey.nupkg'." + Copy-Item $_ "$chocoPkgDirectory\chocolatey.nupkg" -Force -ErrorAction SilentlyContinue + } + } + } + } + } } function Install-ChocolateyBinFiles { -param( - [string] $chocolateyPath, - [string] $chocolateyExePath -) - Write-Debug "Install-ChocolateyBinFiles" - Write-Debug "Installing the bin file redirects" - $redirectsPath = Join-Path $chocolateyPath 'redirects' - if (!(Test-Path "$redirectsPath")) { - Write-ChocolateyWarning "$redirectsPath does not exist" - return - } - - $exeFiles = Get-ChildItem "$redirectsPath" -include @("*.exe","*.cmd") -recurse - foreach ($exeFile in $exeFiles) { - $exeFilePath = $exeFile.FullName - $exeFileName = [System.IO.Path]::GetFileName("$exeFilePath") - $binFilePath = Join-Path $chocolateyExePath $exeFileName - $binFilePathRename = $binFilePath + '.old' - $batchFilePath = $binFilePath.Replace(".exe",".bat") - $bashFilePath = $binFilePath.Replace(".exe","") - if (Test-Path ($batchFilePath)) { Remove-Item $batchFilePath -force -ErrorAction SilentlyContinue } - if (Test-Path ($bashFilePath)) { Remove-Item $bashFilePath -force -ErrorAction SilentlyContinue } - if (Test-Path ($binFilePathRename)) { - try { - Write-Debug "Attempting to remove $binFilePathRename" - Remove-Item $binFilePathRename -force -ErrorAction Stop - } - catch { - Write-ChocolateyWarning "Was not able to remove `'$binFilePathRename`'. This may cause errors." - } - } - if (Test-Path ($binFilePath)) { - try { - Write-Debug "Attempting to rename $binFilePath to $binFilePathRename" - Move-Item -path $binFilePath -destination $binFilePathRename -force -ErrorAction Stop - } - catch { - Write-ChocolateyWarning "Was not able to rename `'$binFilePath`' to `'$binFilePathRename`'." - } + param( + [string] $chocolateyPath, + [string] $chocolateyExePath + ) + Write-Debug "Install-ChocolateyBinFiles" + Write-Debug "Installing the bin file redirects" + $redirectsPath = Join-Path $chocolateyPath 'redirects' + if (!(Test-Path "$redirectsPath")) { + Write-ChocolateyWarning "$redirectsPath does not exist" + return } - try { - Write-Debug "Attempting to copy $exeFilePath to $binFilePath" - Copy-Item -path $exeFilePath -destination $binFilePath -force -ErrorAction Stop - } - catch { - Write-ChocolateyWarning "Was not able to replace `'$binFilePath`' with `'$exeFilePath`'. You may need to do this manually." - } + $exeFiles = Get-ChildItem "$redirectsPath" -Include @("*.exe", "*.cmd") -Recurse + foreach ($exeFile in $exeFiles) { + $exeFilePath = $exeFile.FullName + $exeFileName = [System.IO.Path]::GetFileName("$exeFilePath") + $binFilePath = Join-Path $chocolateyExePath $exeFileName + $binFilePathRename = $binFilePath + '.old' + $batchFilePath = $binFilePath.Replace(".exe", ".bat") + $bashFilePath = $binFilePath.Replace(".exe", "") + if (Test-Path ($batchFilePath)) { + Remove-Item $batchFilePath -Force -ErrorAction SilentlyContinue + } + if (Test-Path ($bashFilePath)) { + Remove-Item $bashFilePath -Force -ErrorAction SilentlyContinue + } + if (Test-Path ($binFilePathRename)) { + try { + Write-Debug "Attempting to remove $binFilePathRename" + Remove-Item $binFilePathRename -Force -ErrorAction Stop + } + catch { + Write-ChocolateyWarning "Was not able to remove `'$binFilePathRename`'. This may cause errors." + } + } + if (Test-Path ($binFilePath)) { + try { + Write-Debug "Attempting to rename $binFilePath to $binFilePathRename" + Move-Item -Path $binFilePath -Destination $binFilePathRename -Force -ErrorAction Stop + } + catch { + Write-ChocolateyWarning "Was not able to rename `'$binFilePath`' to `'$binFilePathRename`'." + } + } + + try { + Write-Debug "Attempting to copy $exeFilePath to $binFilePath" + Copy-Item -Path $exeFilePath -Destination $binFilePath -Force -ErrorAction Stop + } + catch { + Write-ChocolateyWarning "Was not able to replace `'$binFilePath`' with `'$exeFilePath`'. You may need to do this manually." + } - $commandShortcut = [System.IO.Path]::GetFileNameWithoutExtension("$exeFilePath") - Write-Debug "Added command $commandShortcut" - } + $commandShortcut = [System.IO.Path]::GetFileNameWithoutExtension("$exeFilePath") + Write-Debug "Added command $commandShortcut" + } } function Initialize-ChocolateyPath { -param( - [string]$chocolateyExePath = "$($env:ALLUSERSPROFILE)\chocolatey\bin", - [string]$chocolateyExePathVariable = "%$($chocoInstallVariableName)%\bin" -) - Write-Debug "Initialize-ChocolateyPath" - Write-Debug "Initializing Chocolatey Path if required" - $environmentTarget = [System.EnvironmentVariableTarget]::User - if (Test-ProcessAdminRights) { - Write-Debug "Administrator installing so using Machine environment variable target instead of User." - $environmentTarget = [System.EnvironmentVariableTarget]::Machine - } else { - Write-ChocolateyWarning "Setting ChocolateyInstall Path on USER PATH and not SYSTEM Path.`n This is due to either non-administrator install OR the process you are running is not being run as an Administrator." - } - - Install-ChocolateyPath -pathToInstall "$chocolateyExePath" -pathType $environmentTarget + param( + [string]$chocolateyExePath = "$($env:ALLUSERSPROFILE)\chocolatey\bin", + [string]$chocolateyExePathVariable = "%$($chocoInstallVariableName)%\bin" + ) + Write-Debug "Initialize-ChocolateyPath" + Write-Debug "Initializing Chocolatey Path if required" + $environmentTarget = [System.EnvironmentVariableTarget]::User + if (Test-ProcessAdminRights) { + Write-Debug "Administrator installing so using Machine environment variable target instead of User." + $environmentTarget = [System.EnvironmentVariableTarget]::Machine + } + else { + Write-ChocolateyWarning "Setting ChocolateyInstall Path on USER PATH and not SYSTEM Path.`n This is due to either non-administrator install OR the process you are running is not being run as an Administrator." + } + + Install-ChocolateyPath -pathToInstall "$chocolateyExePath" -pathType $environmentTarget } function Process-ChocolateyBinFiles { -param( - [string]$chocolateyExePath = "$($env:ALLUSERSPROFILE)\chocolatey\bin", - [string]$chocolateyExePathVariable = "%$($chocoInstallVariableName)%\bin" -) - Write-Debug "Process-ChocolateyBinFiles" - $processedMarkerFile = Join-Path $chocolateyExePath '_processed.txt' - if (!(test-path $processedMarkerFile)) { - $files = get-childitem $chocolateyExePath -include *.bat -recurse - if ($files -ne $null -and $files.Count -gt 0) { - Write-Debug "Processing Bin files" - foreach ($file in $files) { - Write-Output "Processing $($file.Name) to make it portable" - $fileStream = [System.IO.File]::Open("$file", 'Open', 'Read', 'ReadWrite') - $reader = New-Object System.IO.StreamReader($fileStream) - $fileText = $reader.ReadToEnd() - $reader.Close() - $fileStream.Close() - - $fileText = $fileText.ToLower().Replace("`"" + $chocolateyPath.ToLower(), "SET DIR=%~dp0%`n""%DIR%..\").Replace("\\","\") - - Set-Content $file -Value $fileText -Encoding Ascii - } - } - - Set-Content $processedMarkerFile -Value "$([System.DateTime]::Now.Date)" -Encoding Ascii - } + param( + [string]$chocolateyExePath = "$($env:ALLUSERSPROFILE)\chocolatey\bin", + [string]$chocolateyExePathVariable = "%$($chocoInstallVariableName)%\bin" + ) + Write-Debug "Process-ChocolateyBinFiles" + $processedMarkerFile = Join-Path $chocolateyExePath '_processed.txt' + if (!(Test-Path $processedMarkerFile)) { + $files = Get-ChildItem $chocolateyExePath -Include *.bat -Recurse + if ($files -ne $null -and $files.Count -gt 0) { + Write-Debug "Processing Bin files" + foreach ($file in $files) { + Write-Output "Processing $($file.Name) to make it portable" + $fileStream = [System.IO.File]::Open("$file", 'Open', 'Read', 'ReadWrite') + $reader = New-Object System.IO.StreamReader($fileStream) + $fileText = $reader.ReadToEnd() + $reader.Close() + $fileStream.Close() + + $fileText = $fileText.ToLower().Replace("`"" + $chocolateyPath.ToLower(), "SET DIR=%~dp0%`n""%DIR%..\").Replace("\\", "\") + + Set-Content $file -Value $fileText -Encoding Ascii + } + } + + Set-Content $processedMarkerFile -Value "$([System.DateTime]::Now.Date)" -Encoding Ascii + } } # Adapted from http://www.west-wind.com/Weblog/posts/197245.aspx function Get-FileEncoding($Path) { if ($PSVersionTable.PSVersion.Major -lt 6) { - Write-Debug "Detected Powershell version < 6 ; Using -Encoding byte parameter" - $bytes = [byte[]](Get-Content $Path -Encoding byte -ReadCount 4 -TotalCount 4) + Write-Debug "Detected Powershell version < 6 ; Using -Encoding byte parameter" + $bytes = [byte[]](Get-Content $Path -Encoding byte -ReadCount 4 -TotalCount 4) } else { - Write-Debug "Detected Powershell version >= 6 ; Using -AsByteStream parameter" - $bytes = [byte[]](Get-Content $Path -AsByteStream -ReadCount 4 -TotalCount 4) + Write-Debug "Detected Powershell version >= 6 ; Using -AsByteStream parameter" + $bytes = [byte[]](Get-Content $Path -AsByteStream -ReadCount 4 -TotalCount 4) } - if(!$bytes) { return 'utf8' } + if (!$bytes) { + return 'utf8' + } - switch -regex ('{0:x2}{1:x2}{2:x2}{3:x2}' -f $bytes[0],$bytes[1],$bytes[2],$bytes[3]) { - '^efbbbf' { return 'utf8' } - '^2b2f76' { return 'utf7' } - '^fffe' { return 'unicode' } - '^feff' { return 'bigendianunicode' } - '^0000feff' { return 'utf32' } - default { return 'ascii' } + switch -regex ('{0:x2}{1:x2}{2:x2}{3:x2}' -f $bytes[0], $bytes[1], $bytes[2], $bytes[3]) { + '^efbbbf' { + return 'utf8' + } + '^2b2f76' { + return 'utf7' + } + '^fffe' { + return 'unicode' + } + '^feff' { + return 'bigendianunicode' + } + '^0000feff' { + return 'utf32' + } + default { + return 'ascii' + } } } function Add-ChocolateyProfile { - Write-Debug "Add-ChocolateyProfile" - try { - $profileFile = "$profile" - if ($profileFile -eq $null -or $profileFile -eq '') { - Write-Output 'Not setting tab completion: Profile variable ($profile) resulted in an empty string.' - return - } + Write-Debug "Add-ChocolateyProfile" + try { + $profileFile = "$profile" + if ($profileFile -eq $null -or $profileFile -eq '') { + Write-Output 'Not setting tab completion: Profile variable ($profile) resulted in an empty string.' + return + } - $profileDirectory = (Split-Path -Parent $profileFile) + $profileDirectory = (Split-Path -Parent $profileFile) - if ($env:ChocolateyNoProfile -ne $null -and $env:ChocolateyNoProfile -ne '') { - Write-Warning "Not setting tab completion: Environment variable "ChocolateyNoProfile" exists and is set." - return - } + if ($env:ChocolateyNoProfile -ne $null -and $env:ChocolateyNoProfile -ne '') { + Write-Warning "Not setting tab completion: Environment variable "ChocolateyNoProfile" exists and is set." + return + } - $localSystem = Get-LocalizedWellKnownPrincipalName -WellKnownSidType ([Security.Principal.WellKnownSidType]::LocalSystemSid) - # get current user - $currentUser = [Security.Principal.WindowsIdentity]::GetCurrent() - if ($currentUser.Name -eq $localSystem) { - Write-Warning "Not setting tab completion: Current user is SYSTEM user." - return - } + $localSystem = Get-LocalizedWellKnownPrincipalName -WellKnownSidType ([Security.Principal.WellKnownSidType]::LocalSystemSid) + # get current user + $currentUser = [Security.Principal.WindowsIdentity]::GetCurrent() + if ($currentUser.Name -eq $localSystem) { + Write-Warning "Not setting tab completion: Current user is SYSTEM user." + return + } - if (!(Test-Path($profileDirectory))) { - Write-Debug "Creating '$profileDirectory'" - New-Item "$profileDirectory" -Type Directory -Force -ErrorAction SilentlyContinue | Out-Null - } + if (!(Test-Path($profileDirectory))) { + Write-Debug "Creating '$profileDirectory'" + New-Item "$profileDirectory" -Type Directory -Force -ErrorAction SilentlyContinue | Out-Null + } - if (!(Test-Path($profileFile))) { - Write-Warning "Not setting tab completion: Profile file does not exist at '$profileFile'." - return + if (!(Test-Path($profileFile))) { + Write-Warning "Not setting tab completion: Profile file does not exist at '$profileFile'." + return - #Write-Debug "Creating '$profileFile'" - #"" | Out-File $profileFile -Encoding UTF8 - } + #Write-Debug "Creating '$profileFile'" + #"" | Out-File $profileFile -Encoding UTF8 + } - # Check authenticode, but only if file is greater than 5 bytes - $profileFileInfo = New-Object System.IO.FileInfo($profileFile) - if ($profileFileInfo.Length -gt 5) { - $signature = Get-AuthenticodeSignature $profile - if ($signature.Status -ne 'NotSigned') { - Write-Warning "Not setting tab completion: File is Authenticode signed at '$profile'." - return - } - } + # Check authenticode, but only if file is greater than 5 bytes + $profileFileInfo = New-Object System.IO.FileInfo($profileFile) + if ($profileFileInfo.Length -gt 5) { + $signature = Get-AuthenticodeSignature $profile + if ($signature.Status -ne 'NotSigned') { + Write-Warning "Not setting tab completion: File is Authenticode signed at '$profile'." + return + } + } - $profileInstall = @' + $profileInstall = @' # Import the Chocolatey Profile that contains the necessary code to enable # tab-completions to function for `choco`. @@ -707,24 +739,24 @@ if (Test-Path($ChocolateyProfile)) { } '@ - $chocoProfileSearch = '$ChocolateyProfile' - if(Select-String -Path $profileFile -Pattern $chocoProfileSearch -Quiet -SimpleMatch) { - Write-Debug "Chocolatey profile is already installed." - return - } + $chocoProfileSearch = '$ChocolateyProfile' + if (Select-String -Path $profileFile -Pattern $chocoProfileSearch -Quiet -SimpleMatch) { + Write-Debug "Chocolatey profile is already installed." + return + } - Write-Output 'Adding Chocolatey to the profile. This will provide tab completion, refreshenv, etc.' - $profileInstall | Out-File $profileFile -Append -Encoding (Get-FileEncoding $profileFile) - Write-ChocolateyWarning 'Chocolatey profile installed. Reload your profile - type . $profile' + Write-Output 'Adding Chocolatey to the profile. This will provide tab completion, refreshenv, etc.' + $profileInstall | Out-File $profileFile -Append -Encoding (Get-FileEncoding $profileFile) + Write-ChocolateyWarning 'Chocolatey profile installed. Reload your profile - type . $profile' - if ($PSVersionTable.PSVersion.Major -lt 3) { - Write-ChocolateyWarning "Tab completion does not currently work in PowerShell v2. `n Please upgrade to a more recent version of PowerShell to take advantage of tab completion." - #Write-ChocolateyWarning "To load tab expansion, you need to install PowerTab. `n See https://powertab.codeplex.com/ for details." + if ($PSVersionTable.PSVersion.Major -lt 3) { + Write-ChocolateyWarning "Tab completion does not currently work in PowerShell v2. `n Please upgrade to a more recent version of PowerShell to take advantage of tab completion." + #Write-ChocolateyWarning "To load tab expansion, you need to install PowerTab. `n See https://powertab.codeplex.com/ for details." + } } - - } catch { - Write-ChocolateyWarning "Unable to add Chocolatey to the profile. You will need to do it manually. Error was '$_'" -@' + catch { + Write-ChocolateyWarning "Unable to add Chocolatey to the profile. You will need to do it manually. Error was '$_'" + @' This is how add the Chocolatey Profile manually. Find your $profile. Then add the following lines to it: @@ -733,78 +765,81 @@ if (Test-Path($ChocolateyProfile)) { Import-Module "$ChocolateyProfile" } '@ | Write-Output - } + } } $netFx48InstallTries = 0 function Install-DotNet48IfMissing { -param( - $forceFxInstall = $false -) - # we can't take advantage of any chocolatey module functions, because they - # haven't been unpacked because they require .NET Framework 4.8 - - Write-Debug "Install-DotNet48IfMissing called with `$forceFxInstall=$forceFxInstall" - $NetFxArch = "Framework" - if ([IntPtr]::Size -eq 8) {$NetFxArch="Framework64" } - - $NetFx48Url = 'https://download.visualstudio.microsoft.com/download/pr/2d6bb6b2-226a-4baa-bdec-798822606ff1/8494001c276a4b96804cde7829c04d7f/ndp48-x86-x64-allos-enu.exe' - $NetFx48Path = "$tempDir" - $NetFx48InstallerFile = 'ndp48-x86-x64-allos-enu.exe' - $NetFx48Installer = Join-Path $NetFx48Path $NetFx48InstallerFile - - if (((Get-ItemProperty "HKLM:\SOFTWARE\Microsoft\NET Framework Setup\NDP\v4\Full" -ErrorAction SilentlyContinue).Release -lt 528040) -or $forceFxInstall) { - Write-Output "The registry key for .Net 4.8 was not found or this is forced" - - if (Test-Path "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Component Based Servicing\RebootPending") { - Write-Warning "A reboot is required. `n If you encounter errors, reboot the system and attempt the operation again" - } - - $netFx48InstallTries += 1 - - if (!(Test-Path $NetFx48Installer)) { - Write-Output "Downloading `'$NetFx48Url`' to `'$NetFx48Installer`' - the installer is 100+ MBs, so this could take a while on a slow connection." - (New-Object Net.WebClient).DownloadFile("$NetFx48Url","$NetFx48Installer") - } - - $psi = New-Object System.Diagnostics.ProcessStartInfo - $psi.WorkingDirectory = "$NetFx48Path" - $psi.FileName = "$NetFx48InstallerFile" - # https://msdn.microsoft.com/library/ee942965(v=VS.100).aspx#command_line_options - # http://blogs.msdn.com/b/astebner/archive/2010/05/12/10011664.aspx - # For the actual setup.exe (if you want to unpack first) - /repair /x86 /x64 /ia64 /parameterfolder Client /q /norestart - $psi.Arguments = "/q /norestart" - - Write-Output "Installing `'$NetFx48Installer`' - this may take awhile with no output." - $s = [System.Diagnostics.Process]::Start($psi); - $s.WaitForExit(); - if ($s.ExitCode -eq 1641 -or $s.ExitCode -eq 3010) { - throw ".NET Framework 4.8 was installed, but a reboot is required. `n Please reboot the system and try to install/upgrade Chocolatey again." - } - if ($s.ExitCode -ne 0) { - if ($netFx48InstallTries -ge 2) { - Write-ChocolateyError ".NET Framework install failed with exit code `'$($s.ExitCode)`'. `n This will cause the rest of the install to fail." - throw "Error installing .NET Framework 4.8 (exit code $($s.ExitCode)). `n Please install the .NET Framework 4.8 manually and reboot the system `n and then try to install/upgrade Chocolatey again. `n Download at `'$NetFx48Url`'" - } else { - Write-ChocolateyWarning "Try #$netFx48InstallTries of .NET framework install failed with exit code `'$($s.ExitCode)`'. Trying again." - Install-DotNet48IfMissing $true - } - } - } + param( + $forceFxInstall = $false + ) + # we can't take advantage of any chocolatey module functions, because they + # haven't been unpacked because they require .NET Framework 4.8 + + Write-Debug "Install-DotNet48IfMissing called with `$forceFxInstall=$forceFxInstall" + $NetFxArch = "Framework" + if ([IntPtr]::Size -eq 8) { + $NetFxArch = "Framework64" + } + + $NetFx48Url = 'https://download.visualstudio.microsoft.com/download/pr/2d6bb6b2-226a-4baa-bdec-798822606ff1/8494001c276a4b96804cde7829c04d7f/ndp48-x86-x64-allos-enu.exe' + $NetFx48Path = "$tempDir" + $NetFx48InstallerFile = 'ndp48-x86-x64-allos-enu.exe' + $NetFx48Installer = Join-Path $NetFx48Path $NetFx48InstallerFile + + if (((Get-ItemProperty "HKLM:\SOFTWARE\Microsoft\NET Framework Setup\NDP\v4\Full" -ErrorAction SilentlyContinue).Release -lt 528040) -or $forceFxInstall) { + Write-Output "The registry key for .Net 4.8 was not found or this is forced" + + if (Test-Path "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Component Based Servicing\RebootPending") { + Write-Warning "A reboot is required. `n If you encounter errors, reboot the system and attempt the operation again" + } + + $netFx48InstallTries += 1 + + if (!(Test-Path $NetFx48Installer)) { + Write-Output "Downloading `'$NetFx48Url`' to `'$NetFx48Installer`' - the installer is 100+ MBs, so this could take a while on a slow connection." + (New-Object Net.WebClient).DownloadFile("$NetFx48Url","$NetFx48Installer") + } + + $psi = New-Object System.Diagnostics.ProcessStartInfo + $psi.WorkingDirectory = "$NetFx48Path" + $psi.FileName = "$NetFx48InstallerFile" + # https://msdn.microsoft.com/library/ee942965(v=VS.100).aspx#command_line_options + # http://blogs.msdn.com/b/astebner/archive/2010/05/12/10011664.aspx + # For the actual setup.exe (if you want to unpack first) - /repair /x86 /x64 /ia64 /parameterfolder Client /q /norestart + $psi.Arguments = "/q /norestart" + + Write-Output "Installing `'$NetFx48Installer`' - this may take awhile with no output." + $s = [System.Diagnostics.Process]::Start($psi); + $s.WaitForExit(); + if ($s.ExitCode -eq 1641 -or $s.ExitCode -eq 3010) { + throw ".NET Framework 4.8 was installed, but a reboot is required. `n Please reboot the system and try to install/upgrade Chocolatey again." + } + if ($s.ExitCode -ne 0) { + if ($netFx48InstallTries -ge 2) { + Write-ChocolateyError ".NET Framework install failed with exit code `'$($s.ExitCode)`'. `n This will cause the rest of the install to fail." + throw "Error installing .NET Framework 4.8 (exit code $($s.ExitCode)). `n Please install the .NET Framework 4.8 manually and reboot the system `n and then try to install/upgrade Chocolatey again. `n Download at `'$NetFx48Url`'" + } else { + Write-ChocolateyWarning "Try #$netFx48InstallTries of .NET framework install failed with exit code `'$($s.ExitCode)`'. Trying again." + Install-DotNet48IfMissing $true + } + } + } } function Invoke-Chocolatey-Initial { - Write-Debug "Initializing Chocolatey files, etc by running Chocolatey..." - - try { - $chocoInstallationFolder = Get-ChocolateyInstallFolder - $chocoExe = Join-Path -Path $chocoInstallationFolder -ChildPath "choco.exe" - & $chocoExe -v | Out-Null - Write-Debug "Chocolatey execution completed successfully." - } catch { - Write-ChocolateyWarning "Unable to run Chocolatey at this time. It is likely that .Net Framework installation requires a system reboot" - } + Write-Debug "Initializing Chocolatey files, etc by running Chocolatey..." + + try { + $chocoInstallationFolder = Get-ChocolateyInstallFolder + $chocoExe = Join-Path -Path $chocoInstallationFolder -ChildPath "choco.exe" + & $chocoExe -v | Out-Null + Write-Debug "Chocolatey execution completed successfully." + } + catch { + Write-ChocolateyWarning "Unable to run Chocolatey at this time. It is likely that .Net Framework installation requires a system reboot" + } } -Export-ModuleMember -function Initialize-Chocolatey; +Export-ModuleMember -Function Initialize-Chocolatey; diff --git a/nuspec/chocolatey/chocolatey/tools/init.ps1 b/nuspec/chocolatey/chocolatey/tools/init.ps1 index e82b0c84b5..1030a5726e 100644 --- a/nuspec/chocolatey/chocolatey/tools/init.ps1 +++ b/nuspec/chocolatey/chocolatey/tools/init.ps1 @@ -1,20 +1,20 @@ param($installPath, $toolsPath, $package, $project) $modules = Get-ChildItem $ToolsPath -Filter *.psm1 -$modules | ForEach-Object { import-module -name $_.FullName } +$modules | ForEach-Object { Import-Module -Name $_.FullName } @" ======================== Chocolatey ======================== -Welcome to Chocolatey, your local machine repository built on the NuGet infrastructure. Chocolatey allows you to install application packages to your machine with the goodness of a #chocolatey #nuget combo. +Welcome to Chocolatey, your local machine repository built on the NuGet infrastructure. Chocolatey allows you to install application packages to your machine with the goodness of a #chocolatey #nuget combo. Application executables get added to the path automatically so you can call them from anywhere (command line/powershell prompt), not just in Visual Studio. Lets get Chocolatey! ---------- Visual Studio - ---------- -Please run Initialize-Chocolatey one time per machine to set up the repository. +Please run Initialize-Chocolatey one time per machine to set up the repository. If you are upgrading, please remember to run Initialize-Chocolatey again. After you have run Initialize-Chocolatey, you can safely uninstall the chocolatey package from your current Visual Studio solution. ---------- diff --git a/setup.ps1 b/setup.ps1 index 159973991e..02d95bcbf2 100644 --- a/setup.ps1 +++ b/setup.ps1 @@ -1,6 +1,6 @@ ### install chocolatey ### -if(-not $env:ChocolateyInstall -or -not (Test-Path "$env:ChocolateyInstall")){ - Invoke-Expression ((new-object net.webclient).DownloadString("https://community.chocolatey.org/install.ps1")) +if (-not $env:ChocolateyInstall -or -not (Test-Path "$env:ChocolateyInstall")) { + Invoke-Expression ((New-Object net.webclient).DownloadString("https://community.chocolatey.org/install.ps1")) } cinst pester -version 2.0.2 diff --git a/src/chocolatey.resources/helpers/ChocolateyTabExpansion.ps1 b/src/chocolatey.resources/helpers/ChocolateyTabExpansion.ps1 index 3988f77547..2a6085299f 100644 --- a/src/chocolatey.resources/helpers/ChocolateyTabExpansion.ps1 +++ b/src/chocolatey.resources/helpers/ChocolateyTabExpansion.ps1 @@ -26,14 +26,16 @@ $script:choco = "$env:ChocolateyInstall\choco.exe" function script:chocoCmdOperations($commands, $command, $filter, $currentArguments) { $currentOptions = @('zzzz') - if ($currentArguments -ne $null -and $currentArguments.Trim() -ne '') { $currentOptions = $currentArguments.Trim() -split ' ' } + if ($currentArguments -ne $null -and $currentArguments.Trim() -ne '') { + $currentOptions = $currentArguments.Trim() -split ' ' + } - $commands.$command.Replace(" "," ") -split ' ' | - Where-Object { $_ -notmatch "^(?:$($currentOptions -join '|' -replace "=", "\="))(?:\S*)\s?$" } | - Where-Object { $_ -like "$filter*" } + $commands.$command.Replace(" ", " ") -split ' ' | + Where-Object { $_ -notmatch "^(?:$($currentOptions -join '|' -replace "=", "\="))(?:\S*)\s?$" } | + Where-Object { $_ -like "$filter*" } } -$script:someCommands = @('-?','search','list','info','install','outdated','upgrade','uninstall','new','download','optimize','pack','push','sync','-h','--help','pin','source','config','feature','apikey','export','help','template','--version') +$script:someCommands = @('-?', 'search', 'list', 'info', 'install', 'outdated', 'upgrade', 'uninstall', 'new', 'download', 'optimize', 'pack', 'push', 'sync', '-h', '--help', 'pin', 'source', 'config', 'feature', 'apikey', 'export', 'help', 'template', '--version') # ensure these all have a space to start, or they will cause issues $allcommands = " --debug --verbose --trace --noop --help --accept-license --confirm --limit-output --no-progress --log-file='' --execution-timeout='' --cache-location='' --proxy='' --proxy-user='' --proxy-password='' --proxy-bypass-list='' --proxy-bypass-on-local --force --no-color --skip-compatibility-checks" @@ -48,31 +50,31 @@ $proOutdatedOptions = " --use-self-service" $proPushOptions = " --use-self-service" $commandOptions = @{ - list = "--lo --id-only --pre --exact --by-id-only --id-starts-with --detailed --approved-only --not-broken --source='' --user='' --password='' --local-only --prerelease --include-programs --page='' --page-size='' --order-by-popularity --download-cache-only --disable-package-repository-optimizations" + $proListOptions + $allcommands - search = "--pre --exact --by-id-only --id-starts-with --detailed --approved-only --not-broken --source='' --user='' --password='' --local-only --prerelease --include-programs --page='' --page-size='' --order-by-popularity --download-cache-only --disable-package-repository-optimizations" + $proListOptions + $allcommands - info = "--pre --lo --source='' --user='' --password='' --local-only --prerelease --disable-package-repository-optimizations" + $proInfoOptions + $allcommands - install = "-y -whatif -? --pre --version= --params='' --install-arguments='' --override-arguments --ignore-dependencies --source='' --source='windowsfeatures' --source='webpi' --user='' --password='' --prerelease --forcex86 --not-silent --package-parameters='' --exit-when-reboot-detected --ignore-detected-reboot --allow-downgrade --force-dependencies --require-checksums --use-package-exit-codes --ignore-package-exit-codes --skip-automation-scripts --allow-multiple-versions --ignore-checksums --allow-empty-checksums --allow-empty-checksums-secure --download-checksum='' --download-checksum-type='' --download-checksum-x64='' --download-checksum-type-x64='' --stop-on-first-package-failure --disable-package-repository-optimizations --pin" + $proInstallUpgradeOptions + $allcommands - pin = "--name='' --version='' -?" + $proPinOptions + $allcommands - outdated = "-? --source='' --user='' --password='' --ignore-pinned --ignore-unfound --pre --prerelease --disable-package-repository-optimizations" + $proOutdatedOptions + $allcommands - upgrade = "-y -whatif -? --pre --version='' --except='' --params='' --install-arguments='' --override-arguments --ignore-dependencies --source='' --source='windowsfeatures' --source='webpi' --user='' --password='' --prerelease --forcex86 --not-silent --package-parameters='' --exit-when-reboot-detected --ignore-detected-reboot --allow-downgrade --allow-multiple-versions --require-checksums --use-package-exit-codes --ignore-package-exit-codes --skip-automation-scripts --fail-on-unfound --fail-on-not-installed --ignore-checksums --allow-empty-checksums --allow-empty-checksums-secure --download-checksum='' --download-checksum-type='' --download-checksum-x64='' --download-checksum-type-x64='' --exclude-prerelease --stop-on-first-package-failure --use-remembered-options --ignore-remembered-options --skip-when-not-installed --install-if-not-installed --disable-package-repository-optimizations --pin" + $proInstallUpgradeOptions + $proUpgradeOptions + $allcommands - uninstall = "-y -whatif -? --force-dependencies --remove-dependencies --all-versions --source='windowsfeatures' --source='webpi' --version= --uninstall-arguments='' --override-arguments --not-silent --params='' --package-parameters='' --exit-when-reboot-detected --ignore-detected-reboot --use-package-exit-codes --ignore-package-exit-codes --skip-automation-scripts --use-autouninstaller --skip-autouninstaller --fail-on-autouninstaller --ignore-autouninstaller-failure --stop-on-first-package-failure" + $proUninstallOptions + $allcommands - new = "--template-name='' --output-directory='' --automaticpackage --version='' --maintainer='' packageversion='' maintainername='' maintainerrepo='' installertype='' url='' url64='' silentargs='' --use-built-in-template -?" + $proNewOptions + $allcommands - pack = "--version='' --output-directory='' -?" + $allcommands - push = "--source='' --api-key='' --timeout='' -?" + $proPushOptions + $allcommands - source = "--name='' --source='' --user='' --password='' --priority= --bypass-proxy --allow-self-service -?" + $allcommands - config = "--name='' --value='' -?" + $allcommands - feature = "--name='' -?" + $allcommands - apikey = "--source='' --api-key='' --remove -?" + $allcommands - download = "--internalize --internalize-all-urls --ignore-dependencies --installed-packages --ignore-unfound-packages --resources-location='' --download-location='' --outputdirectory='' --source='' --version='' --prerelease --user='' --password='' --cert='' --certpassword='' --append-use-original-location --recompile --disable-package-repository-optimizations -? --use-self-service" + $allcommands - sync = "--output-directory='' --id='' --package-id='' -? --use-self-service" + $allcommands - optimize = "--deflate-nupkg-only --id='' -? --use-self-service" + $allcommands - export = "--include-version-numbers --output-file-path='' -?" + $allcommands - template = "--name=''" + $allcommands + list = "--lo --id-only --pre --exact --by-id-only --id-starts-with --detailed --approved-only --not-broken --source='' --user='' --password='' --local-only --prerelease --include-programs --page='' --page-size='' --order-by-popularity --download-cache-only --disable-package-repository-optimizations" + $proListOptions + $allcommands + search = "--pre --exact --by-id-only --id-starts-with --detailed --approved-only --not-broken --source='' --user='' --password='' --local-only --prerelease --include-programs --page='' --page-size='' --order-by-popularity --download-cache-only --disable-package-repository-optimizations" + $proListOptions + $allcommands + info = "--pre --lo --source='' --user='' --password='' --local-only --prerelease --disable-package-repository-optimizations" + $proInfoOptions + $allcommands + install = "-y -whatif -? --pre --version= --params='' --install-arguments='' --override-arguments --ignore-dependencies --source='' --source='windowsfeatures' --source='webpi' --user='' --password='' --prerelease --forcex86 --not-silent --package-parameters='' --exit-when-reboot-detected --ignore-detected-reboot --allow-downgrade --force-dependencies --require-checksums --use-package-exit-codes --ignore-package-exit-codes --skip-automation-scripts --allow-multiple-versions --ignore-checksums --allow-empty-checksums --allow-empty-checksums-secure --download-checksum='' --download-checksum-type='' --download-checksum-x64='' --download-checksum-type-x64='' --stop-on-first-package-failure --disable-package-repository-optimizations --pin" + $proInstallUpgradeOptions + $allcommands + pin = "--name='' --version='' -?" + $proPinOptions + $allcommands + outdated = "-? --source='' --user='' --password='' --ignore-pinned --ignore-unfound --pre --prerelease --disable-package-repository-optimizations" + $proOutdatedOptions + $allcommands + upgrade = "-y -whatif -? --pre --version='' --except='' --params='' --install-arguments='' --override-arguments --ignore-dependencies --source='' --source='windowsfeatures' --source='webpi' --user='' --password='' --prerelease --forcex86 --not-silent --package-parameters='' --exit-when-reboot-detected --ignore-detected-reboot --allow-downgrade --allow-multiple-versions --require-checksums --use-package-exit-codes --ignore-package-exit-codes --skip-automation-scripts --fail-on-unfound --fail-on-not-installed --ignore-checksums --allow-empty-checksums --allow-empty-checksums-secure --download-checksum='' --download-checksum-type='' --download-checksum-x64='' --download-checksum-type-x64='' --exclude-prerelease --stop-on-first-package-failure --use-remembered-options --ignore-remembered-options --skip-when-not-installed --install-if-not-installed --disable-package-repository-optimizations --pin" + $proInstallUpgradeOptions + $proUpgradeOptions + $allcommands + uninstall = "-y -whatif -? --force-dependencies --remove-dependencies --all-versions --source='windowsfeatures' --source='webpi' --version= --uninstall-arguments='' --override-arguments --not-silent --params='' --package-parameters='' --exit-when-reboot-detected --ignore-detected-reboot --use-package-exit-codes --ignore-package-exit-codes --skip-automation-scripts --use-autouninstaller --skip-autouninstaller --fail-on-autouninstaller --ignore-autouninstaller-failure --stop-on-first-package-failure" + $proUninstallOptions + $allcommands + new = "--template-name='' --output-directory='' --automaticpackage --version='' --maintainer='' packageversion='' maintainername='' maintainerrepo='' installertype='' url='' url64='' silentargs='' --use-built-in-template -?" + $proNewOptions + $allcommands + pack = "--version='' --output-directory='' -?" + $allcommands + push = "--source='' --api-key='' --timeout='' -?" + $proPushOptions + $allcommands + source = "--name='' --source='' --user='' --password='' --priority= --bypass-proxy --allow-self-service -?" + $allcommands + config = "--name='' --value='' -?" + $allcommands + feature = "--name='' -?" + $allcommands + apikey = "--source='' --api-key='' --remove -?" + $allcommands + download = "--internalize --internalize-all-urls --ignore-dependencies --installed-packages --ignore-unfound-packages --resources-location='' --download-location='' --outputdirectory='' --source='' --version='' --prerelease --user='' --password='' --cert='' --certpassword='' --append-use-original-location --recompile --disable-package-repository-optimizations -? --use-self-service" + $allcommands + sync = "--output-directory='' --id='' --package-id='' -? --use-self-service" + $allcommands + optimize = "--deflate-nupkg-only --id='' -? --use-self-service" + $allcommands + export = "--include-version-numbers --output-file-path='' -?" + $allcommands + template = "--name=''" + $allcommands } try { - # if license exists - # add in pro/biz switches + # if license exists + # add in pro/biz switches } catch { } @@ -81,7 +83,8 @@ function script:chocoCommands($filter) { $cmdList = @() if (-not $global:ChocolateyTabSettings.AllCommands) { $cmdList += $someCommands -like "$filter*" - } else { + } + else { $cmdList += (& $script:choco -h) | Where-Object { $_ -match '^ \S.*' } | ForEach-Object { $_.Split(' ', [StringSplitOptions]::RemoveEmptyEntries) } | @@ -92,122 +95,129 @@ function script:chocoCommands($filter) { } function script:chocoLocalPackages($filter) { - if ($filter -ne $null -and $filter.StartsWith(".")) { return; } #file search + if ($filter -ne $null -and $filter.StartsWith(".")) { + return; + } #file search @(& $script:choco list $filter -lo -r --id-starts-with) | ForEach-Object { $_.Split('|')[0] } } function script:chocoLocalPackagesUpgrade($filter) { - if ($filter -ne $null -and $filter.StartsWith(".")) { return; } #file search - @('all|') + @(& $script:choco list $filter -lo -r --id-starts-with) | - Where-Object { $_ -like "$filter*" } | - ForEach-Object { $_.Split('|')[0] } + if ($filter -ne $null -and $filter.StartsWith(".")) { + return; + } #file search + @('all|') + @(& $script:choco list $filter -lo -r --id-starts-with) | + Where-Object { $_ -like "$filter*" } | + ForEach-Object { $_.Split('|')[0] } } function script:chocoRemotePackages($filter) { - if ($filter -ne $null -and $filter.StartsWith(".")) { return; } #file search - @('packages.config|') + @(& $script:choco search $filter --page='0' --page-size='30' -r --id-starts-with --order-by-popularity) | - Where-Object { $_ -like "$filter*" } | - ForEach-Object { $_.Split('|')[0] } + if ($filter -ne $null -and $filter.StartsWith(".")) { + return; + } #file search + @('packages.config|') + @(& $script:choco search $filter --page='0' --page-size='30' -r --id-starts-with --order-by-popularity) | + Where-Object { $_ -like "$filter*" } | + ForEach-Object { $_.Split('|')[0] } } function Get-AliasPattern($exe) { - $aliases = @($exe) + @(Get-Alias | Where-Object { $_.Definition -eq $exe } | Select-Object -Exp Name) + $aliases = @($exe) + @(Get-Alias | Where-Object { $_.Definition -eq $exe } | Select-Object -Exp Name) - "($($aliases -join '|'))" + "($($aliases -join '|'))" } function ChocolateyTabExpansion($lastBlock) { - switch -regex ($lastBlock -replace "^$(Get-AliasPattern choco) ","") { - - # Handles uninstall package names - "^uninstall\s+(?[^\.][^-\s]*)$" { - chocoLocalPackages $matches['package'] - } - - # Handles install package names - "^(install)\s+(?[^\.][^-\s]+)$" { - chocoRemotePackages $matches['package'] - } - - # Handles upgrade / uninstall package names - "^upgrade\s+(?[^\.][^-\s]*)$" { - chocoLocalPackagesUpgrade $matches['package'] - } - - # Handles list/search first tab - "^(list|search)\s+(?[^-\s]*)$" { - @('','-?') | Where-Object { $_ -like "$($matches['subcommand'])*" } - } - - # Handles new first tab - "^(new)\s+(?[^-\s]*)$" { - @('','-?') | Where-Object { $_ -like "$($matches['subcommand'])*" } - } - - # Handles pack first tab - "^(pack)\s+(?[^-\s]*)$" { - @('','-?') | Where-Object { $_ -like "$($matches['subcommand'])*" } - } - - # Handles push first tab - "^(push)\s+(?[^-\s]*)$" { - @('','-?') | Where-Object { $_ -like "$($matches['subcommand'])*" } - } - - # Handles source first tab - "^(source)\s+(?[^-\s]*)$" { - @('list','add','remove','disable','enable','-?') | Where-Object { $_ -like "$($matches['subcommand'])*" } + switch -regex ($lastBlock -replace "^$(Get-AliasPattern choco) ", "") { + + # Handles uninstall package names + "^uninstall\s+(?[^\.][^-\s]*)$" { + chocoLocalPackages $matches['package'] + } + + # Handles install package names + "^(install)\s+(?[^\.][^-\s]+)$" { + chocoRemotePackages $matches['package'] + } + + # Handles upgrade / uninstall package names + "^upgrade\s+(?[^\.][^-\s]*)$" { + chocoLocalPackagesUpgrade $matches['package'] + } + + # Handles list/search first tab + "^(list|search)\s+(?[^-\s]*)$" { + @('', '-?') | Where-Object { $_ -like "$($matches['subcommand'])*" } + } + + # Handles new first tab + "^(new)\s+(?[^-\s]*)$" { + @('', '-?') | Where-Object { $_ -like "$($matches['subcommand'])*" } + } + + # Handles pack first tab + "^(pack)\s+(?[^-\s]*)$" { + @('', '-?') | Where-Object { $_ -like "$($matches['subcommand'])*" } + } + + # Handles push first tab + "^(push)\s+(?[^-\s]*)$" { + @('', '-?') | Where-Object { $_ -like "$($matches['subcommand'])*" } + } + + # Handles source first tab + "^(source)\s+(?[^-\s]*)$" { + @('list', 'add', 'remove', 'disable', 'enable', '-?') | Where-Object { $_ -like "$($matches['subcommand'])*" } + } + + # Handles pin first tab + "^(pin)\s+(?[^-\s]*)$" { + @('list', 'add', 'remove', '-?') | Where-Object { $_ -like "$($matches['subcommand'])*" } + } + + # Handles feature first tab + "^(feature)\s+(?[^-\s]*)$" { + @('list', 'disable', 'enable', '-?') | Where-Object { $_ -like "$($matches['subcommand'])*" } + } + # Handles config first tab + "^(config)\s+(?[^-\s]*)$" { + @('list', 'get', 'set', 'unset', '-?') | Where-Object { $_ -like "$($matches['subcommand'])*" } + } + + # Handles template first tab + "^(template)\s+(?[^-\s]*)$" { + @('list', 'info', '-?') | Where-Object { $_ -like "$($matches['subcommand'])*" } + } + + # Handles more options after others + "^(?$($commandOptions.Keys -join '|'))(?.*)\s+(?\S*)$" { + chocoCmdOperations $commandOptions $matches['cmd'] $matches['op'] $matches['currentArguments'] + } + + # Handles choco + "^(?$($commandOptions.Keys -join '|'))\s+(?\S*)$" { + chocoCmdOperations $commandOptions $matches['cmd'] $matches['op'] + } + + # Handles choco + "^(?\S*)$" { + chocoCommands $matches['cmd'] + } } - - # Handles pin first tab - "^(pin)\s+(?[^-\s]*)$" { - @('list','add','remove','-?') | Where-Object { $_ -like "$($matches['subcommand'])*" } - } - - # Handles feature first tab - "^(feature)\s+(?[^-\s]*)$" { - @('list','disable','enable','-?') | Where-Object { $_ -like "$($matches['subcommand'])*" } - } - # Handles config first tab - "^(config)\s+(?[^-\s]*)$" { - @('list','get','set','unset','-?') | Where-Object { $_ -like "$($matches['subcommand'])*" } - } - - # Handles template first tab - "^(template)\s+(?[^-\s]*)$" { - @('list', 'info', '-?') | Where-Object { $_ -like "$($matches['subcommand'])*" } - } - - # Handles more options after others - "^(?$($commandOptions.Keys -join '|'))(?.*)\s+(?\S*)$" { - chocoCmdOperations $commandOptions $matches['cmd'] $matches['op'] $matches['currentArguments'] - } - - # Handles choco - "^(?$($commandOptions.Keys -join '|'))\s+(?\S*)$" { - chocoCmdOperations $commandOptions $matches['cmd'] $matches['op'] - } - - # Handles choco - "^(?\S*)$" { - chocoCommands $matches['cmd'] - } - } } -$PowerTab_RegisterTabExpansion = if (Get-Module -Name powertab) { Get-Command Register-TabExpansion -Module powertab -ErrorAction SilentlyContinue } -if ($PowerTab_RegisterTabExpansion) -{ - & $PowerTab_RegisterTabExpansion "choco" -Type Command { - param($Context, [ref]$TabExpansionHasOutput, [ref]$QuoteSpaces) # 1: +$PowerTab_RegisterTabExpansion = if (Get-Module -Name powertab) { + Get-Command Register-TabExpansion -Module powertab -ErrorAction SilentlyContinue +} +if ($PowerTab_RegisterTabExpansion) { + & $PowerTab_RegisterTabExpansion "choco" -Type Command { + param($Context, [ref]$TabExpansionHasOutput, [ref]$QuoteSpaces) # 1: - $line = $Context.Line - $lastBlock = [System.Text.RegularExpressions.Regex]::Split($line, '[|;]')[-1].TrimStart() - $TabExpansionHasOutput.Value = $true - ChocolateyTabExpansion $lastBlock - } + $line = $Context.Line + $lastBlock = [System.Text.RegularExpressions.Regex]::Split($line, '[|;]')[-1].TrimStart() + $TabExpansionHasOutput.Value = $true + ChocolateyTabExpansion $lastBlock + } - return + return } if (Test-Path Function:\TabExpansion) { @@ -219,9 +229,15 @@ function TabExpansion($line, $lastWord) { switch -regex ($lastBlock) { # Execute Chocolatey tab completion for all choco-related commands - "^$(Get-AliasPattern choco) (.*)" { ChocolateyTabExpansion $lastBlock } + "^$(Get-AliasPattern choco) (.*)" { + ChocolateyTabExpansion $lastBlock + } # Fall back on existing tab expansion - default { if (Test-Path Function:\TabExpansionBackup) { TabExpansionBackup $line $lastWord } } + default { + if (Test-Path Function:\TabExpansionBackup) { + TabExpansionBackup $line $lastWord + } + } } } diff --git a/src/chocolatey.resources/helpers/chocolateyProfile.psm1 b/src/chocolatey.resources/helpers/chocolateyProfile.psm1 index 33d64e1cff..b76f6448fc 100644 --- a/src/chocolatey.resources/helpers/chocolateyProfile.psm1 +++ b/src/chocolatey.resources/helpers/chocolateyProfile.psm1 @@ -3,20 +3,22 @@ # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. -# + # You may obtain a copy of the License at -# + # http://www.apache.org/licenses/LICENSE-2.0 -# + # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. -if (Get-Module chocolateyProfile) { return } +if (Get-Module chocolateyProfile) { + return +} -$thisDirectory = (Split-Path -parent $MyInvocation.MyCommand.Definition) +$thisDirectory = (Split-Path -Parent $MyInvocation.MyCommand.Definition) . $thisDirectory\functions\Write-FunctionCallLogMessage.ps1 . $thisDirectory\functions\Get-EnvironmentVariable.ps1 diff --git a/src/chocolatey.resources/helpers/chocolateyScriptRunner.ps1 b/src/chocolatey.resources/helpers/chocolateyScriptRunner.ps1 index 7557d347c9..9b36bdcbe8 100644 --- a/src/chocolatey.resources/helpers/chocolateyScriptRunner.ps1 +++ b/src/chocolatey.resources/helpers/chocolateyScriptRunner.ps1 @@ -1,18 +1,22 @@ param( - [alias("ia","installArgs")][string] $installArguments = '', - [alias("o","override","overrideArguments","notSilent")] - [switch] $overrideArgs = $false, - [alias("x86")][switch] $forceX86 = $false, - [alias("params","parameters","pkgParams")][string]$packageParameters = '', - [string]$packageScript, - [string[]]$preRunHookScripts, - [string[]]$postRunHookScripts + [alias("ia", "installArgs")][string] $installArguments = '', + [alias("o", "override", "overrideArguments", "notSilent")] + [switch] $overrideArgs = $false, + [alias("x86")][switch] $forceX86 = $false, + [alias("params", "parameters", "pkgParams")][string]$packageParameters = '', + [string]$packageScript, + [string[]]$preRunHookScripts, + [string[]]$postRunHookScripts ) $global:DebugPreference = "SilentlyContinue" -if ($env:ChocolateyEnvironmentDebug -eq 'true') { $global:DebugPreference = "Continue"; } +if ($env:ChocolateyEnvironmentDebug -eq 'true') { + $global:DebugPreference = "Continue"; +} $global:VerbosePreference = "SilentlyContinue" -if ($env:ChocolateyEnvironmentVerbose -eq 'true') { $global:VerbosePreference = "Continue"; $verbosity = $true } +if ($env:ChocolateyEnvironmentVerbose -eq 'true') { + $global:VerbosePreference = "Continue"; $verbosity = $true +} Write-Debug '---------------------------Script Execution---------------------------' Write-Debug "Running 'ChocolateyScriptRunner' for $($env:packageName) v$($env:packageVersion) with packageScript '$packageScript', packageFolder:'$($env:packageFolder)', installArguments: '$installArguments', packageParameters: '$packageParameters', preRunHookScripts: '$preRunHookScripts', postRunHookScripts: '$postRunHookScripts'," @@ -33,8 +37,8 @@ $packageName = $env:packageName $packageVersion = $env:packageVersion $packageFolder = $env:packageFolder -$helpersPath = (Split-Path -parent $MyInvocation.MyCommand.Definition); -$nugetChocolateyPath = (Split-Path -parent $helpersPath) +$helpersPath = (Split-Path -Parent $MyInvocation.MyCommand.Definition); +$nugetChocolateyPath = (Split-Path -Parent $helpersPath) $nugetPath = $nugetChocolateyPath $nugetExePath = Join-Path $nuGetPath 'bin' $nugetLibPath = Join-Path $nuGetPath 'lib' @@ -62,24 +66,24 @@ $scriptSuccess = $? $lastExecutableExitCode = $LASTEXITCODE if ($lastExecutableExitCode -ne $null -and $lastExecutableExitCode -ne '') { - Write-Debug "The last executable that ran had an exit code of '$lastExecutableExitCode'." + Write-Debug "The last executable that ran had an exit code of '$lastExecutableExitCode'." } if (-not $scriptSuccess) { - Write-Debug "The script exited with a failure." + Write-Debug "The script exited with a failure." } $exitCode = 0 if ($exitCode -eq 0 -and -not $scriptSuccess) { - $exitCode = 1 + $exitCode = 1 } if ($env:ChocolateyExitCode -ne $null -and $env:ChocolateyExitCode -ne '') { - $exitCode = $env:ChocolateyExitCode + $exitCode = $env:ChocolateyExitCode } if ($exitCode -ne $null -and $exitCode -ne '' -and $exitCode -ne 0) { - Set-PowerShellExitCode $exitCode + Set-PowerShellExitCode $exitCode } if ($PSBoundParameters.ContainsKey('postRunHookScripts')) { diff --git a/src/chocolatey.resources/helpers/functions/Format-FileSize.ps1 b/src/chocolatey.resources/helpers/functions/Format-FileSize.ps1 index 914fb63491..cf79134f29 100644 --- a/src/chocolatey.resources/helpers/functions/Format-FileSize.ps1 +++ b/src/chocolatey.resources/helpers/functions/Format-FileSize.ps1 @@ -15,7 +15,7 @@ # limitations under the License. Function Format-FileSize { -<# + <# .SYNOPSIS DO NOT USE. Not part of the public API. @@ -46,19 +46,19 @@ Format-FileSize -Size $fileSizeBytes .LINK Get-WebFile #> -param ( - [Parameter(Mandatory=$true, Position=0)][double] $size, - [parameter(ValueFromRemainingArguments = $true)][Object[]] $ignoredArguments -) + param ( + [Parameter(Mandatory = $true, Position = 0)][double] $size, + [parameter(ValueFromRemainingArguments = $true)][Object[]] $ignoredArguments + ) - # Do not log function call, it interrupts the single line download progress output. + # Do not log function call, it interrupts the single line download progress output. - Foreach ($unit in @('B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB')) { - If ($size -lt 1024) { - return [string]::Format("{0:0.##} {1}", $size, $unit) + Foreach ($unit in @('B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB')) { + If ($size -lt 1024) { + return [string]::Format("{0:0.##} {1}", $size, $unit) + } + $size /= 1024 } - $size /= 1024 - } - return [string]::Format("{0:0.##} YB", $size) + return [string]::Format("{0:0.##} YB", $size) } diff --git a/src/chocolatey.resources/helpers/functions/Get-CheckSumValid.ps1 b/src/chocolatey.resources/helpers/functions/Get-CheckSumValid.ps1 index 2687383f44..0c94845661 100644 --- a/src/chocolatey.resources/helpers/functions/Get-CheckSumValid.ps1 +++ b/src/chocolatey.resources/helpers/functions/Get-CheckSumValid.ps1 @@ -15,7 +15,7 @@ # limitations under the License. function Get-ChecksumValid { -<# + <# .SYNOPSIS Checks a file's checksum versus a passed checksum and checksum type. @@ -116,102 +116,107 @@ Get-ChocolateyWebFile .LINK Install-ChocolateyPackage #> -param( - [parameter(Mandatory=$true, Position=0)][string] $file, - [parameter(Mandatory=$false, Position=1)][string] $checksum = '', - [parameter(Mandatory=$false, Position=2)][string] $checksumType = 'md5', - [parameter(Mandatory=$false, Position=3)][string] $originalUrl = '', - [parameter(ValueFromRemainingArguments = $true)][Object[]] $ignoredArguments -) - - Write-FunctionCallLogMessage -Invocation $MyInvocation -Parameters $PSBoundParameters - - if ($env:ChocolateyIgnoreChecksums -eq 'true') { - Write-Warning "Ignoring checksums due to feature checksumFiles turned off or option --ignore-checksums set." - return - } - - if ($checksum -eq '' -or $checksum -eq $null) { - $allowEmptyChecksums = $env:ChocolateyAllowEmptyChecksums - $allowEmptyChecksumsSecure = $env:ChocolateyAllowEmptyChecksumsSecure - if ($allowEmptyChecksums -eq 'true') { - Write-Debug "Empty checksums are allowed due to allowEmptyChecksums feature or option." - return + param( + [parameter(Mandatory = $true, Position = 0)][string] $file, + [parameter(Mandatory = $false, Position = 1)][string] $checksum = '', + [parameter(Mandatory = $false, Position = 2)][string] $checksumType = 'md5', + [parameter(Mandatory = $false, Position = 3)][string] $originalUrl = '', + [parameter(ValueFromRemainingArguments = $true)][Object[]] $ignoredArguments + ) + + Write-FunctionCallLogMessage -Invocation $MyInvocation -Parameters $PSBoundParameters + + if ($env:ChocolateyIgnoreChecksums -eq 'true') { + Write-Warning "Ignoring checksums due to feature checksumFiles turned off or option --ignore-checksums set." + return } - if ($originalUrl -ne $null -and $originalUrl.ToLower().StartsWith("https") -and $allowEmptyChecksumsSecure -eq 'true') { - Write-Debug "Download from HTTPS source with feature 'allowEmptyChecksumsSecure' enabled." - return + if ($checksum -eq '' -or $checksum -eq $null) { + $allowEmptyChecksums = $env:ChocolateyAllowEmptyChecksums + $allowEmptyChecksumsSecure = $env:ChocolateyAllowEmptyChecksumsSecure + if ($allowEmptyChecksums -eq 'true') { + Write-Debug "Empty checksums are allowed due to allowEmptyChecksums feature or option." + return + } + + if ($originalUrl -ne $null -and $originalUrl.ToLower().StartsWith("https") -and $allowEmptyChecksumsSecure -eq 'true') { + Write-Debug "Download from HTTPS source with feature 'allowEmptyChecksumsSecure' enabled." + return + } + + Write-Warning "Missing package checksums are not allowed (by default for HTTP/FTP, `n HTTPS when feature 'allowEmptyChecksumsSecure' is disabled) for `n safety and security reasons. Although we strongly advise against it, `n if you need this functionality, please set the feature `n 'allowEmptyChecksums' ('choco feature enable -n `n allowEmptyChecksums') `n or pass in the option '--allow-empty-checksums'. You can also pass `n checksums at runtime (recommended). See `choco install -?` for details." + Write-Debug "If you are a maintainer attempting to determine the checksum for packaging purposes, please run `n 'choco install checksum' and run 'checksum -t sha256 -f $file' `n Ensure you do this for all remote resources." + if ($PSVersionTable.PSVersion.Major -ge 4) { + Write-Debug "Because you are running PowerShell with a major version of v4 or greater, you could also opt to run `n '(Get-FileHash -Path $file -Algorithm SHA256).Hash' `n rather than install a separate tool." + } + + if ($env:ChocolateyPowerShellHost -eq 'true') { + $statement = "The integrity of the file '$([System.IO.Path]::GetFileName($file))'" + if ($originalUrl -ne $null -and $originalUrl -ne '') { + $statement += " from '$originalUrl'" + } + $statement += " has not been verified by a checksum in the package scripts." + $question = 'Do you wish to allow the install to continue (not recommended)?' + $choices = New-Object System.Collections.ObjectModel.Collection[System.Management.Automation.Host.ChoiceDescription] + $choices.Add((New-Object System.Management.Automation.Host.ChoiceDescription -ArgumentList '&Yes')) + $choices.Add((New-Object System.Management.Automation.Host.ChoiceDescription -ArgumentList '&No')) + + $selection = $Host.UI.PromptForChoice($statement, $question, $choices, 1) + + if ($selection -eq 0) { + return + } + } + + if ($originalUrl -ne $null -and $originalUrl.ToLower().StartsWith("https")) { + throw "This package downloads over HTTPS but does not yet have package checksums to verify the package. We recommend asking the maintainer to add checksums to this package. In the meantime if you need this package to work correctly, please enable the feature allowEmptyChecksumsSecure, provide the runtime switch '--allow-empty-checksums-secure', or pass in checksums at runtime (recommended - see 'choco install -?' / 'choco upgrade -?' for details)." + } + else { + throw "Empty checksums are no longer allowed by default for non-secure sources. Please ask the maintainer to add checksums to this package. In the meantime if you need this package to work correctly, please enable the feature allowEmptyChecksums, provide the runtime switch '--allow-empty-checksums', or pass in checksums at runtime (recommended - see 'choco install -?' / 'choco upgrade -?' for details). It is strongly advised against allowing empty checksums for non-internal HTTP/FTP sources." + } } - Write-Warning "Missing package checksums are not allowed (by default for HTTP/FTP, `n HTTPS when feature 'allowEmptyChecksumsSecure' is disabled) for `n safety and security reasons. Although we strongly advise against it, `n if you need this functionality, please set the feature `n 'allowEmptyChecksums' ('choco feature enable -n `n allowEmptyChecksums') `n or pass in the option '--allow-empty-checksums'. You can also pass `n checksums at runtime (recommended). See `choco install -?` for details." - Write-Debug "If you are a maintainer attempting to determine the checksum for packaging purposes, please run `n 'choco install checksum' and run 'checksum -t sha256 -f $file' `n Ensure you do this for all remote resources." - if ($PSVersionTable.PSVersion.Major -ge 4){ - Write-Debug "Because you are running PowerShell with a major version of v4 or greater, you could also opt to run `n '(Get-FileHash -Path $file -Algorithm SHA256).Hash' `n rather than install a separate tool." + if (!([System.IO.File]::Exists($file))) { + throw "Unable to checksum a file that doesn't exist - Could not find file `'$file`'" } - if ($env:ChocolateyPowerShellHost -eq 'true') { - $statement = "The integrity of the file '$([System.IO.Path]::GetFileName($file))'" - if ($originalUrl -ne $null -and $originalUrl -ne '') { - $statement += " from '$originalUrl'" - } - $statement += " has not been verified by a checksum in the package scripts." - $question = 'Do you wish to allow the install to continue (not recommended)?' - $choices = New-Object System.Collections.ObjectModel.Collection[System.Management.Automation.Host.ChoiceDescription] - $choices.Add((New-Object System.Management.Automation.Host.ChoiceDescription -ArgumentList '&Yes')) - $choices.Add((New-Object System.Management.Automation.Host.ChoiceDescription -ArgumentList '&No')) - - $selection = $Host.UI.PromptForChoice($statement, $question, $choices, 1) - - if ($selection -eq 0) { return } + if ($checksumType -eq $null -or $checksumType -eq '') { + $checksumType = 'md5' } - if ($originalUrl -ne $null -and $originalUrl.ToLower().StartsWith("https")) { - throw "This package downloads over HTTPS but does not yet have package checksums to verify the package. We recommend asking the maintainer to add checksums to this package. In the meantime if you need this package to work correctly, please enable the feature allowEmptyChecksumsSecure, provide the runtime switch '--allow-empty-checksums-secure', or pass in checksums at runtime (recommended - see 'choco install -?' / 'choco upgrade -?' for details)." - } else { - throw "Empty checksums are no longer allowed by default for non-secure sources. Please ask the maintainer to add checksums to this package. In the meantime if you need this package to work correctly, please enable the feature allowEmptyChecksums, provide the runtime switch '--allow-empty-checksums', or pass in checksums at runtime (recommended - see 'choco install -?' / 'choco upgrade -?' for details). It is strongly advised against allowing empty checksums for non-internal HTTP/FTP sources." + if ($checksumType -ne 'sha1' -and $checksumType -ne 'sha256' -and $checksumType -ne 'sha512' -and $checksumType -ne 'md5') { + Write-Debug 'Setting checksumType to md5 due to non-set value or type is not specified correctly.' + throw "Checksum type '$checksumType' is unsupported. This type may be supported in a newer version of Chocolatey." } - } - - if (!([System.IO.File]::Exists($file))) { throw "Unable to checksum a file that doesn't exist - Could not find file `'$file`'" } - - if ($checksumType -eq $null -or $checksumType -eq ''){ - $checksumType = 'md5' - } - if ($checksumType -ne 'sha1' -and $checksumType -ne 'sha256' -and $checksumType -ne 'sha512' -and $checksumType -ne 'md5') { - Write-Debug 'Setting checksumType to md5 due to non-set value or type is not specified correctly.' - throw "Checksum type '$checksumType' is unsupported. This type may be supported in a newer version of Chocolatey." - } - - $checksumExe = Join-Path "$helpersPath" '..\tools\checksum.exe' - if (!([System.IO.File]::Exists($checksumExe))) { - Update-SessionEnvironment - $checksumExe = Join-Path "$env:ChocolateyInstall" 'tools\checksum.exe' - } - Write-Debug "checksum.exe found at `'$checksumExe`'" + $checksumExe = Join-Path "$helpersPath" '..\tools\checksum.exe' + if (!([System.IO.File]::Exists($checksumExe))) { + Update-SessionEnvironment + $checksumExe = Join-Path "$env:ChocolateyInstall" 'tools\checksum.exe' + } + Write-Debug "checksum.exe found at `'$checksumExe`'" - $params = "-c=`"$checksum`" -t=`"$checksumType`" -f=`"$file`"" + $params = "-c=`"$checksum`" -t=`"$checksumType`" -f=`"$file`"" - Write-Debug "Executing command ['$checksumExe' $params]" - $process = New-Object System.Diagnostics.Process - $process.StartInfo = New-Object System.Diagnostics.ProcessStartInfo($checksumExe, $params) - $process.StartInfo.UseShellExecute = $false - $process.StartInfo.WindowStyle = [System.Diagnostics.ProcessWindowStyle]::Hidden + Write-Debug "Executing command ['$checksumExe' $params]" + $process = New-Object System.Diagnostics.Process + $process.StartInfo = New-Object System.Diagnostics.ProcessStartInfo($checksumExe, $params) + $process.StartInfo.UseShellExecute = $false + $process.StartInfo.WindowStyle = [System.Diagnostics.ProcessWindowStyle]::Hidden - $process.Start() | Out-Null - $process.WaitForExit() - $exitCode = $process.ExitCode - $process.Dispose() + $process.Start() | Out-Null + $process.WaitForExit() + $exitCode = $process.ExitCode + $process.Dispose() - Write-Debug "Command [`'$checksumExe`' $params] exited with `'$exitCode`'." + Write-Debug "Command [`'$checksumExe`' $params] exited with `'$exitCode`'." - if ($exitCode -ne 0) { - throw "Checksum for '$file' did not meet '$checksum' for checksum type '$checksumType'. Consider passing the actual checksums through with `--checksum --checksum64` once you validate the checksums are appropriate. A less secure option is to pass `--ignore-checksums` if necessary." - } + if ($exitCode -ne 0) { + throw "Checksum for '$file' did not meet '$checksum' for checksum type '$checksumType'. Consider passing the actual checksums through with `--checksum --checksum64` once you validate the checksums are appropriate. A less secure option is to pass `--ignore-checksums` if necessary." + } - #$fileCheckSumActual = $md5Output.Split(' ')[0] - # if ($fileCheckSumActual -ne $checkSum) { - # throw "CheckSum for `'$file'` did not meet `'$checkSum`'." - # } + #$fileCheckSumActual = $md5Output.Split(' ')[0] + # if ($fileCheckSumActual -ne $checkSum) { + # throw "CheckSum for `'$file'` did not meet `'$checkSum`'." + # } } diff --git a/src/chocolatey.resources/helpers/functions/Get-ChocolateyPath.ps1 b/src/chocolatey.resources/helpers/functions/Get-ChocolateyPath.ps1 index bc04cfa223..6a6ba5b9c2 100644 --- a/src/chocolatey.resources/helpers/functions/Get-ChocolateyPath.ps1 +++ b/src/chocolatey.resources/helpers/functions/Get-ChocolateyPath.ps1 @@ -14,7 +14,7 @@ # limitations under the License. function Get-ChocolateyPath { -<# + <# .SYNOPSIS Retrieve the paths available to be used by maintainers of packages. @@ -46,7 +46,7 @@ Allows splatting with arguments that do not apply. Do not use directly. $path = Get-ChocolateyPath -PathType 'PackagePath' #> param( - [parameter(Mandatory=$true)] + [parameter(Mandatory = $true)] [alias('type')] [string] $pathType ) @@ -56,9 +56,11 @@ $path = Get-ChocolateyPath -PathType 'PackagePath' 'PackagePath' { if (Test-Path Env:\ChocolateyPackagePath) { $result = "$env:ChocolateyPackagePath" - } elseif (Test-Path Env:\PackagePath) { + } + elseif (Test-Path Env:\PackagePath) { $result = "$env:PackagePath" - } else { + } + else { $installPath = Get-ChocolateyPath -pathType 'InstallPath' $result = "$installPath\lib\$env:ChocolateyPackageName" } @@ -66,9 +68,11 @@ $path = Get-ChocolateyPath -PathType 'PackagePath' 'InstallPath' { if (Test-Path Env:\ChocolateyInstall) { $result = "$env:ChocolateyInstall" - } elseif (Test-Path Env:\ProgramData) { + } + elseif (Test-Path Env:\ProgramData) { $result = "$env:ProgramData\chocolatey" - } else { + } + else { $result = "$env:SystemDrive\ProgramData\chocolatey" } } diff --git a/src/chocolatey.resources/helpers/functions/Get-ChocolateyUnzip.ps1 b/src/chocolatey.resources/helpers/functions/Get-ChocolateyUnzip.ps1 index d4acdadeef..3acaea9860 100644 --- a/src/chocolatey.resources/helpers/functions/Get-ChocolateyUnzip.ps1 +++ b/src/chocolatey.resources/helpers/functions/Get-ChocolateyUnzip.ps1 @@ -15,7 +15,7 @@ # limitations under the License. function Get-ChocolateyUnzip { -<# + <# .SYNOPSIS Unzips an archive file and returns the location for further processing. @@ -77,7 +77,7 @@ uninstalls .PARAMETER DisableLogging OPTIONAL - This disables logging of the extracted items. It speeds up -extraction of archives with many files. +extraction of archives with many files. Usage of this parameter will prevent Uninstall-ChocolateyZipPackage from working, extracted files will have to be cleaned up with @@ -95,161 +95,189 @@ Get-ChocolateyUnzip -FileFullPath "c:\someFile.zip" -Destination $toolsDir .LINK Install-ChocolateyZipPackage #> -param( - [alias("file")][parameter(Mandatory=$false, Position=0)][string] $fileFullPath, - [alias("unzipLocation")][parameter(Mandatory=$true, Position=1)][string] $destination, - [parameter(Mandatory=$false, Position=2)][string] $specificFolder, - [parameter(Mandatory=$false, Position=3)][string] $packageName, - [alias("file64")][parameter(Mandatory=$false)][string] $fileFullPath64, - [parameter(Mandatory=$false)][switch] $disableLogging, - [parameter(ValueFromRemainingArguments = $true)][Object[]] $ignoredArguments -) - - Write-FunctionCallLogMessage -Invocation $MyInvocation -Parameters $PSBoundParameters - - $bitnessMessage = '' - $zipfileFullPath=$fileFullPath - if ((Get-OSArchitectureWidth 32) -or $env:ChocolateyForceX86 -eq 'true') { - if (!$fileFullPath) { throw "32-bit archive is not supported for $packageName"; } - if ($fileFullPath64) { $bitnessMessage = '32-bit '; } - } elseif ($fileFullPath64) { - $zipfileFullPath = $fileFullPath64 - $bitnessMessage = '64-bit ' - } - - if ($zipfileFullPath -eq '' -or $zipfileFullPath -eq $null) { - throw 'Package parameters incorrect, either FileFullPath or FileFullPath64 must be specified.' - } - - if ($packageName) { - $packagelibPath = $env:ChocolateyPackageFolder - if (!(Test-Path -path $packagelibPath)) { - New-Item $packagelibPath -type directory - } - - $zipFilename=split-path $zipfileFullPath -Leaf - $zipExtractLogFullPath= Join-Path $packagelibPath $zipFilename`.txt - } - - if ($env:chocolateyPackageName -ne $null -and $env:chocolateyPackageName -eq $env:ChocolateyInstallDirectoryPackage) { - Write-Warning "Install Directory override not available for zip packages at this time.`n If this package also runs a native installer using Chocolatey`n functions, the directory will be honored." - } - - Write-Host "Extracting $bitnessMessage$zipfileFullPath to $destination..." - if (![System.IO.Directory]::Exists($destination)) { [System.IO.Directory]::CreateDirectory($destination) | Out-Null } - - $7zip = Join-Path "$helpersPath" '..\tools\7z.exe' - if (!([System.IO.File]::Exists($7zip))) { - Update-SessionEnvironment - $7zip = Join-Path "$env:ChocolateyInstall" 'tools\7z.exe' - } - $7zip = [System.IO.Path]::GetFullPath($7zip) - Write-Debug "7zip found at `'$7zip`'" - - # 32-bit 7z would not find C:\Windows\System32\config\systemprofile\AppData\Local\Temp, - # because it gets translated to C:\Windows\SysWOW64\... by the WOW redirection layer. - # Replace System32 with sysnative, which does not get redirected. - # 32-bit 7z is required so it can see both architectures - if ([IntPtr]::Size -ne 4) { - $fileFullPathNoRedirection = $zipfileFullPath -ireplace ([System.Text.RegularExpressions.Regex]::Escape([Environment]::GetFolderPath('System'))),(Join-Path $Env:SystemRoot 'SysNative') - $destinationNoRedirection = $destination -ireplace ([System.Text.RegularExpressions.Regex]::Escape([Environment]::GetFolderPath('System'))),(Join-Path $Env:SystemRoot 'SysNative') - } else { - $fileFullPathNoRedirection = $zipfileFullPath - $destinationNoRedirection = $destination - } - - $workingDirectory = $(Get-Location -PSProvider 'FileSystem') - if ($workingDirectory -eq $null -or $workingDirectory.ProviderPath -eq $null) { - Write-Debug "Unable to use current location for Working Directory. Using Cache Location instead." - $workingDirectory = $env:TEMP - } - $workingDirectory = $workingDirectory.ProviderPath - - $loggingParam = '-bb1' - if ($disableLogging) { - $loggingParam = '-bb0' - } - - $params = "x -aoa -bd $loggingParam -o`"$destinationNoRedirection`" -y `"$fileFullPathNoRedirection`"" - if ($specificfolder) { - $params += " `"$specificfolder`"" - } - Write-Debug "Executing command ['$7zip' $params]" - - # Capture 7z's output into a StringBuilder and write it out in blocks, to improve I/O performance. - $global:zipFileList = New-Object System.Text.StringBuilder - $global:zipDestinationFolder = $destination - - # Redirecting output slows things down a bit. - $writeOutput = { - if ($EventArgs.Data -ne $null) { - $line = $EventArgs.Data - Write-Verbose "$line" - if ($line.StartsWith("- ")) { - $global:zipFileList.AppendLine($global:zipDestinationFolder + "\" + $line.Substring(2)) - } - } - } - - $writeError = { - if ($EventArgs.Data -ne $null) { - Write-Error "$($EventArgs.Data)" - } - } - - $process = New-Object System.Diagnostics.Process - $process.EnableRaisingEvents = $true - Register-ObjectEvent -InputObject $process -SourceIdentifier "LogOutput_ChocolateyZipProc" -EventName OutputDataReceived -Action $writeOutput | Out-Null - Register-ObjectEvent -InputObject $process -SourceIdentifier "LogErrors_ChocolateyZipProc" -EventName ErrorDataReceived -Action $writeError | Out-Null - - $process.StartInfo = new-object System.Diagnostics.ProcessStartInfo($7zip, $params) - $process.StartInfo.RedirectStandardOutput = $true - $process.StartInfo.RedirectStandardError = $true - $process.StartInfo.UseShellExecute = $false - $process.StartInfo.WorkingDirectory = $workingDirectory - $process.StartInfo.WindowStyle = [System.Diagnostics.ProcessWindowStyle]::Hidden - $process.StartInfo.CreateNoWindow = $true - - $process.Start() | Out-Null - if ($process.StartInfo.RedirectStandardOutput) { $process.BeginOutputReadLine() } - if ($process.StartInfo.RedirectStandardError) { $process.BeginErrorReadLine() } - $process.WaitForExit() - - # For some reason this forces the jobs to finish and waits for - # them to do so. Without this it never finishes. - Unregister-Event -SourceIdentifier "LogOutput_ChocolateyZipProc" - Unregister-Event -SourceIdentifier "LogErrors_ChocolateyZipProc" - - # sometimes the process hasn't fully exited yet. - for ($loopCount=1; $loopCount -le 15; $loopCount++) { - if ($process.HasExited) { break; } - Write-Debug "Waiting for 7z.exe process to exit - $loopCount/15 seconds"; - Start-Sleep 1; - } - - $exitCode = $process.ExitCode - $process.Dispose() - - Set-PowerShellExitCode $exitCode - Write-Debug "Command ['$7zip' $params] exited with `'$exitCode`'." - - if ($zipExtractLogFullPath -and -not $disableLogging) { - Set-Content $zipExtractLogFullPath $global:zipFileList.ToString() -Encoding UTF8 -Force - } - - Write-Debug "7z exit code: $exitCode" - - $errorMessageAddendum = " This is most likely an issue with the '$env:chocolateyPackageName' package and not with Chocolatey itself. Please follow up with the package maintainer(s) directly." - switch ($exitCode) { - 0 { break } - 1 { throw 'Some files could not be extracted.' + $errorMessageAddendum } # this one is returned e.g. for access denied errors - 2 { throw '7-Zip encountered a fatal error while extracting the files.' + $errorMessageAddendum } - 7 { throw ('7-Zip command line error.' + $errorMessageAddendum) } - 8 { throw '7-Zip out of memory.' + $errorMessageAddendum } - 255 { throw 'Extraction cancelled by the user.' + $errorMessageAddendum } - default { throw "7-Zip signalled an unknown error (code $exitCode)" + $errorMessageAddendum} - } - - $env:ChocolateyPackageInstallLocation = $destination - return $destination + param( + [alias("file")][parameter(Mandatory = $false, Position = 0)][string] $fileFullPath, + [alias("unzipLocation")][parameter(Mandatory = $true, Position = 1)][string] $destination, + [parameter(Mandatory = $false, Position = 2)][string] $specificFolder, + [parameter(Mandatory = $false, Position = 3)][string] $packageName, + [alias("file64")][parameter(Mandatory = $false)][string] $fileFullPath64, + [parameter(Mandatory = $false)][switch] $disableLogging, + [parameter(ValueFromRemainingArguments = $true)][Object[]] $ignoredArguments + ) + + Write-FunctionCallLogMessage -Invocation $MyInvocation -Parameters $PSBoundParameters + + $bitnessMessage = '' + $zipfileFullPath = $fileFullPath + if ((Get-OSArchitectureWidth 32) -or $env:ChocolateyForceX86 -eq 'true') { + if (!$fileFullPath) { + throw "32-bit archive is not supported for $packageName"; + } + if ($fileFullPath64) { + $bitnessMessage = '32-bit '; + } + } + elseif ($fileFullPath64) { + $zipfileFullPath = $fileFullPath64 + $bitnessMessage = '64-bit ' + } + + if ($zipfileFullPath -eq '' -or $zipfileFullPath -eq $null) { + throw 'Package parameters incorrect, either FileFullPath or FileFullPath64 must be specified.' + } + + if ($packageName) { + $packagelibPath = $env:ChocolateyPackageFolder + if (!(Test-Path -Path $packagelibPath)) { + New-Item $packagelibPath -type directory + } + + $zipFilename = Split-Path $zipfileFullPath -Leaf + $zipExtractLogFullPath = Join-Path $packagelibPath $zipFilename`.txt + } + + if ($env:chocolateyPackageName -ne $null -and $env:chocolateyPackageName -eq $env:ChocolateyInstallDirectoryPackage) { + Write-Warning "Install Directory override not available for zip packages at this time.`n If this package also runs a native installer using Chocolatey`n functions, the directory will be honored." + } + + Write-Host "Extracting $bitnessMessage$zipfileFullPath to $destination..." + if (![System.IO.Directory]::Exists($destination)) { + [System.IO.Directory]::CreateDirectory($destination) | Out-Null + } + + $7zip = Join-Path "$helpersPath" '..\tools\7z.exe' + if (!([System.IO.File]::Exists($7zip))) { + Update-SessionEnvironment + $7zip = Join-Path "$env:ChocolateyInstall" 'tools\7z.exe' + } + $7zip = [System.IO.Path]::GetFullPath($7zip) + Write-Debug "7zip found at `'$7zip`'" + + # 32-bit 7z would not find C:\Windows\System32\config\systemprofile\AppData\Local\Temp, + # because it gets translated to C:\Windows\SysWOW64\... by the WOW redirection layer. + # Replace System32 with sysnative, which does not get redirected. + # 32-bit 7z is required so it can see both architectures + if ([IntPtr]::Size -ne 4) { + $fileFullPathNoRedirection = $zipfileFullPath -ireplace ([System.Text.RegularExpressions.Regex]::Escape([Environment]::GetFolderPath('System'))), (Join-Path $Env:SystemRoot 'SysNative') + $destinationNoRedirection = $destination -ireplace ([System.Text.RegularExpressions.Regex]::Escape([Environment]::GetFolderPath('System'))), (Join-Path $Env:SystemRoot 'SysNative') + } + else { + $fileFullPathNoRedirection = $zipfileFullPath + $destinationNoRedirection = $destination + } + + $workingDirectory = $(Get-Location -PSProvider 'FileSystem') + if ($workingDirectory -eq $null -or $workingDirectory.ProviderPath -eq $null) { + Write-Debug "Unable to use current location for Working Directory. Using Cache Location instead." + $workingDirectory = $env:TEMP + } + $workingDirectory = $workingDirectory.ProviderPath + + $loggingParam = '-bb1' + if ($disableLogging) { + $loggingParam = '-bb0' + } + + $params = "x -aoa -bd $loggingParam -o`"$destinationNoRedirection`" -y `"$fileFullPathNoRedirection`"" + if ($specificfolder) { + $params += " `"$specificfolder`"" + } + Write-Debug "Executing command ['$7zip' $params]" + + # Capture 7z's output into a StringBuilder and write it out in blocks, to improve I/O performance. + $global:zipFileList = New-Object System.Text.StringBuilder + $global:zipDestinationFolder = $destination + + # Redirecting output slows things down a bit. + $writeOutput = { + if ($EventArgs.Data -ne $null) { + $line = $EventArgs.Data + Write-Verbose "$line" + if ($line.StartsWith("- ")) { + $global:zipFileList.AppendLine($global:zipDestinationFolder + "\" + $line.Substring(2)) + } + } + } + + $writeError = { + if ($EventArgs.Data -ne $null) { + Write-Error "$($EventArgs.Data)" + } + } + + $process = New-Object System.Diagnostics.Process + $process.EnableRaisingEvents = $true + Register-ObjectEvent -InputObject $process -SourceIdentifier "LogOutput_ChocolateyZipProc" -EventName OutputDataReceived -Action $writeOutput | Out-Null + Register-ObjectEvent -InputObject $process -SourceIdentifier "LogErrors_ChocolateyZipProc" -EventName ErrorDataReceived -Action $writeError | Out-Null + + $process.StartInfo = New-Object System.Diagnostics.ProcessStartInfo($7zip, $params) + $process.StartInfo.RedirectStandardOutput = $true + $process.StartInfo.RedirectStandardError = $true + $process.StartInfo.UseShellExecute = $false + $process.StartInfo.WorkingDirectory = $workingDirectory + $process.StartInfo.WindowStyle = [System.Diagnostics.ProcessWindowStyle]::Hidden + $process.StartInfo.CreateNoWindow = $true + + $process.Start() | Out-Null + if ($process.StartInfo.RedirectStandardOutput) { + $process.BeginOutputReadLine() + } + if ($process.StartInfo.RedirectStandardError) { + $process.BeginErrorReadLine() + } + $process.WaitForExit() + + # For some reason this forces the jobs to finish and waits for + # them to do so. Without this it never finishes. + Unregister-Event -SourceIdentifier "LogOutput_ChocolateyZipProc" + Unregister-Event -SourceIdentifier "LogErrors_ChocolateyZipProc" + + # sometimes the process hasn't fully exited yet. + for ($loopCount = 1; $loopCount -le 15; $loopCount++) { + if ($process.HasExited) { + break; + } + Write-Debug "Waiting for 7z.exe process to exit - $loopCount/15 seconds"; + Start-Sleep 1; + } + + $exitCode = $process.ExitCode + $process.Dispose() + + Set-PowerShellExitCode $exitCode + Write-Debug "Command ['$7zip' $params] exited with `'$exitCode`'." + + if ($zipExtractLogFullPath -and -not $disableLogging) { + Set-Content $zipExtractLogFullPath $global:zipFileList.ToString() -Encoding UTF8 -Force + } + + Write-Debug "7z exit code: $exitCode" + + $errorMessageAddendum = " This is most likely an issue with the '$env:chocolateyPackageName' package and not with Chocolatey itself. Please follow up with the package maintainer(s) directly." + switch ($exitCode) { + 0 { + break + } + 1 { + throw 'Some files could not be extracted.' + $errorMessageAddendum + } # this one is returned e.g. for access denied errors + 2 { + throw '7-Zip encountered a fatal error while extracting the files.' + $errorMessageAddendum + } + 7 { + throw ('7-Zip command line error.' + $errorMessageAddendum) + } + 8 { + throw '7-Zip out of memory.' + $errorMessageAddendum + } + 255 { + throw 'Extraction cancelled by the user.' + $errorMessageAddendum + } + default { + throw "7-Zip signalled an unknown error (code $exitCode)" + $errorMessageAddendum + } + } + + $env:ChocolateyPackageInstallLocation = $destination + return $destination } diff --git a/src/chocolatey.resources/helpers/functions/Get-ChocolateyWebFile.ps1 b/src/chocolatey.resources/helpers/functions/Get-ChocolateyWebFile.ps1 index c07996d095..212dd3566d 100644 --- a/src/chocolatey.resources/helpers/functions/Get-ChocolateyWebFile.ps1 +++ b/src/chocolatey.resources/helpers/functions/Get-ChocolateyWebFile.ps1 @@ -15,7 +15,7 @@ # limitations under the License. function Get-ChocolateyWebFile { -<# + <# .SYNOPSIS Downloads a file from the internet. @@ -187,203 +187,241 @@ Get-WebFileName .LINK Get-FtpFile #> -param( - [parameter(Mandatory=$true, Position=0)][string] $packageName, - [parameter(Mandatory=$true, Position=1)][string] $fileFullPath, - [parameter(Mandatory=$false, Position=2)][string] $url = '', - [parameter(Mandatory=$false, Position=3)] - [alias("url64")][string] $url64bit = '', - [parameter(Mandatory=$false)][string] $checksum = '', - [parameter(Mandatory=$false)][string] $checksumType = '', - [parameter(Mandatory=$false)][string] $checksum64 = '', - [parameter(Mandatory=$false)][string] $checksumType64 = $checksumType, - [parameter(Mandatory=$false)][hashtable] $options = @{Headers=@{}}, - [parameter(Mandatory=$false)][switch] $getOriginalFileName, - [parameter(Mandatory=$false)][switch] $forceDownload, - [parameter(ValueFromRemainingArguments = $true)][Object[]] $ignoredArguments -) - - Write-FunctionCallLogMessage -Invocation $MyInvocation -Parameters $PSBoundParameters - - # url overrides - $urlOverride = $env:ChocolateyUrlOverride - $url64bitOverride = $env:ChocolateyUrl64bitOverride - if ($urlOverride -ne $null -and $urlOverride -ne '') { $url = $urlOverride } - if ($url64bitOverride -ne $null -and $url64bitOverride -ne '') { $url64bit = $url64bitOverride } - - if ($url -ne $null) { $url = $url.Replace("//","/").Replace(":/","://") } - if ($url64bit -ne $null) { $url64bit = $url64bit.Replace("//","/").Replace(":/","://") } - - $url32bit = $url - - # allow user provided values for checksumming - $checksum32Override = $env:chocolateyChecksum32 - $checksumType32Override = $env:chocolateyChecksumType32 - $checksum64Override = $env:chocolateyChecksum64 - $checksumType64Override = $env:chocolateyChecksumType64 - if ($checksum32Override -ne $null -and $checksum32Override -ne '') { $checksum = $checksum32Override } - if ($checksumType32Override -ne $null -and $checksumType32Override -ne '') { $checksumType = $checksumType32Override } - if ($checksum64Override -ne $null -and $checksum64Override -ne '') { $checksum64 = $checksum64Override } - if ($checksumType64Override -ne $null -and $checksumType64Override -ne '') { $checksumType64 = $checksumType64Override } - - $checksum32 = $checksum - $checksumType32 = $checksumType - $bitWidth = 32 - if (Get-OSArchitectureWidth 64) { - $bitWidth = 64 - } - Write-Debug "CPU is $bitWidth bit" - - $bitPackage = '' - if ($url32bit -ne $url64bit -and $url64bit -ne $null -and $url64bit -ne '') { $bitPackage = '32 bit' } - - if ($bitWidth -eq 64 -and $url64bit -ne $null -and $url64bit -ne '') { - Write-Debug "Setting url to '$url64bit' and bitPackage to $bitWidth" - $bitPackage = '64 bit' - $url = $url64bit - # only set if urls are different - if ($url32bit -ne $url64bit) { - $checksum = $checksum64 - if ($checkSumType64 -ne '') { - $checksumType = $checksumType64 - } + param( + [parameter(Mandatory = $true, Position = 0)][string] $packageName, + [parameter(Mandatory = $true, Position = 1)][string] $fileFullPath, + [parameter(Mandatory = $false, Position = 2)][string] $url = '', + [parameter(Mandatory = $false, Position = 3)] + [alias("url64")][string] $url64bit = '', + [parameter(Mandatory = $false)][string] $checksum = '', + [parameter(Mandatory = $false)][string] $checksumType = '', + [parameter(Mandatory = $false)][string] $checksum64 = '', + [parameter(Mandatory = $false)][string] $checksumType64 = $checksumType, + [parameter(Mandatory = $false)][hashtable] $options = @{Headers = @{} }, + [parameter(Mandatory = $false)][switch] $getOriginalFileName, + [parameter(Mandatory = $false)][switch] $forceDownload, + [parameter(ValueFromRemainingArguments = $true)][Object[]] $ignoredArguments + ) + + Write-FunctionCallLogMessage -Invocation $MyInvocation -Parameters $PSBoundParameters + + # url overrides + $urlOverride = $env:ChocolateyUrlOverride + $url64bitOverride = $env:ChocolateyUrl64bitOverride + if ($urlOverride -ne $null -and $urlOverride -ne '') { + $url = $urlOverride + } + if ($url64bitOverride -ne $null -and $url64bitOverride -ne '') { + $url64bit = $url64bitOverride } - } - $forceX86 = $env:chocolateyForceX86; - if ($forceX86) { - Write-Debug "User specified -x86 so forcing 32 bit" - if ($url32bit -ne $url64bit) { $bitPackage = '32 bit' } - $url = $url32bit - $checksum = $checksum32 - $checksumType = $checksumType32 - } + if ($url -ne $null) { + $url = $url.Replace("//", "/").Replace(":/", "://") + } + if ($url64bit -ne $null) { + $url64bit = $url64bit.Replace("//", "/").Replace(":/", "://") + } - # If we're on 32 bit or attempting to force 32 bit and there is no - # 32 bit url, we need to throw an error. - if ($url -eq $null -or $url -eq '') { - throw "This package does not support $bitPackage architecture." - } + $url32bit = $url - # determine if the url can be SSL/TLS - if ($url.StartsWith('http:')) { - try { - $httpsUrl = $url.Replace("http://", "https://") - Get-WebHeaders -Url $httpsUrl -ErrorAction "Stop" | Out-Null - $url = $httpsUrl - Write-Warning "Url has SSL/TLS available, switching to HTTPS for download" - } catch { - Write-Debug "Url does not have HTTPS available" + # allow user provided values for checksumming + $checksum32Override = $env:chocolateyChecksum32 + $checksumType32Override = $env:chocolateyChecksumType32 + $checksum64Override = $env:chocolateyChecksum64 + $checksumType64Override = $env:chocolateyChecksumType64 + if ($checksum32Override -ne $null -and $checksum32Override -ne '') { + $checksum = $checksum32Override + } + if ($checksumType32Override -ne $null -and $checksumType32Override -ne '') { + $checksumType = $checksumType32Override + } + if ($checksum64Override -ne $null -and $checksum64Override -ne '') { + $checksum64 = $checksum64Override + } + if ($checksumType64Override -ne $null -and $checksumType64Override -ne '') { + $checksumType64 = $checksumType64Override } - } - if ($getOriginalFileName) { - try { - $fileFullPath = $fileFullPath -replace '\\chocolatey\\chocolatey\\', '\chocolatey\' - $fileDirectory = [System.IO.Path]::GetDirectoryName($fileFullPath) - $originalFileName = [System.IO.Path]::GetFileName($fileFullPath) - $fileFullPath = Get-WebFileName -Url $url -DefaultName $originalFileName - $fileFullPath = Join-Path $fileDirectory $fileFullPath - $fileFullPath = [System.IO.Path]::GetFullPath($fileFullPath) - } catch { - Write-Host "Attempt to use original download file name failed for '$url'." + $checksum32 = $checksum + $checksumType32 = $checksumType + $bitWidth = 32 + if (Get-OSArchitectureWidth 64) { + $bitWidth = 64 } - } + Write-Debug "CPU is $bitWidth bit" - try { - $fileDirectory = $([System.IO.Path]::GetDirectoryName($fileFullPath)) - if (!(Test-Path($fileDirectory))) { - [System.IO.Directory]::CreateDirectory($fileDirectory) | Out-Null + $bitPackage = '' + if ($url32bit -ne $url64bit -and $url64bit -ne $null -and $url64bit -ne '') { + $bitPackage = '32 bit' } - } catch { - Write-Host "Attempt to create directory failed for '$fileFullPath'." - } - $urlIsRemote = $true - $headers = @{} - if ($url.StartsWith('http')) { - try { - $headers = Get-WebHeaders -Url $url -ErrorAction "Stop" - } catch { - if ($PSVersionTable.PSVersion -lt (New-Object 'Version' 3,0)) { - Write-Debug "Converting Security Protocol to SSL3 only for PowerShell v2" - # this should last for the entire duration - $originalProtocol = [System.Net.ServicePointManager]::SecurityProtocol - [System.Net.ServicePointManager]::SecurityProtocol = [System.Net.SecurityProtocolType]::Ssl3 + if ($bitWidth -eq 64 -and $url64bit -ne $null -and $url64bit -ne '') { + Write-Debug "Setting url to '$url64bit' and bitPackage to $bitWidth" + $bitPackage = '64 bit' + $url = $url64bit + # only set if urls are different + if ($url32bit -ne $url64bit) { + $checksum = $checksum64 + if ($checkSumType64 -ne '') { + $checksumType = $checksumType64 + } + } + } + + $forceX86 = $env:chocolateyForceX86; + if ($forceX86) { + Write-Debug "User specified -x86 so forcing 32 bit" + if ($url32bit -ne $url64bit) { + $bitPackage = '32 bit' + } + $url = $url32bit + $checksum = $checksum32 + $checksumType = $checksumType32 + } + + # If we're on 32 bit or attempting to force 32 bit and there is no + # 32 bit url, we need to throw an error. + if ($url -eq $null -or $url -eq '') { + throw "This package does not support $bitPackage architecture." + } + + # determine if the url can be SSL/TLS + if ($url.StartsWith('http:')) { try { - $headers = Get-WebHeaders -Url $url -ErrorAction "Stop" - } catch { - Write-Host "Attempt to get headers for $url failed.`n $($_.Exception.Message)" - [System.Net.ServicePointManager]::SecurityProtocol = $originalProtocol + $httpsUrl = $url.Replace("http://", "https://") + Get-WebHeaders -Url $httpsUrl -ErrorAction "Stop" | Out-Null + $url = $httpsUrl + Write-Warning "Url has SSL/TLS available, switching to HTTPS for download" + } + catch { + Write-Debug "Url does not have HTTPS available" } - } else { - Write-Host "Attempt to get headers for $url failed.`n $($_.Exception.Message)" - } } - $needsDownload = $true - $fiCached = New-Object System.IO.FileInfo($fileFullPath) - if ($fiCached.Exists -and -not ($forceDownload)) { - if ($checksum -ne $null -and $checksum -ne '') { - try { - Write-Host "File appears to be downloaded already. Verifying with package checksum to determine if it needs to be redownloaded." - Get-ChecksumValid -file $fileFullPath -checkSum $checksum -checksumType $checksumType -originalUrl $url -ErrorAction "Stop" - $needsDownload = $false - } catch { - Write-Debug "Existing file failed checksum. Will be redownloaded from url." - } - } - elseif ($headers.Count -ne 0 -and $headers.ContainsKey("Content-Length")) { - # if the file already exists there is no reason to download it again. - if ($fiCached.Length -eq $headers["Content-Length"]) { $needsDownload = $false } - } + if ($getOriginalFileName) { + try { + $fileFullPath = $fileFullPath -replace '\\chocolatey\\chocolatey\\', '\chocolatey\' + $fileDirectory = [System.IO.Path]::GetDirectoryName($fileFullPath) + $originalFileName = [System.IO.Path]::GetFileName($fileFullPath) + $fileFullPath = Get-WebFileName -Url $url -DefaultName $originalFileName + $fileFullPath = Join-Path $fileDirectory $fileFullPath + $fileFullPath = [System.IO.Path]::GetFullPath($fileFullPath) + } + catch { + Write-Host "Attempt to use original download file name failed for '$url'." + } + } + + try { + $fileDirectory = $([System.IO.Path]::GetDirectoryName($fileFullPath)) + if (!(Test-Path($fileDirectory))) { + [System.IO.Directory]::CreateDirectory($fileDirectory) | Out-Null + } + } + catch { + Write-Host "Attempt to create directory failed for '$fileFullPath'." } - if ($needsDownload) { - Write-Host "Downloading $packageName $bitPackage + $urlIsRemote = $true + $headers = @{} + if ($url.StartsWith('http')) { + try { + $headers = Get-WebHeaders -Url $url -ErrorAction "Stop" + } + catch { + if ($PSVersionTable.PSVersion -lt (New-Object 'Version' 3, 0)) { + Write-Debug "Converting Security Protocol to SSL3 only for PowerShell v2" + # this should last for the entire duration + $originalProtocol = [System.Net.ServicePointManager]::SecurityProtocol + [System.Net.ServicePointManager]::SecurityProtocol = [System.Net.SecurityProtocolType]::Ssl3 + try { + $headers = Get-WebHeaders -Url $url -ErrorAction "Stop" + } + catch { + Write-Host "Attempt to get headers for $url failed.`n $($_.Exception.Message)" + [System.Net.ServicePointManager]::SecurityProtocol = $originalProtocol + } + } + else { + Write-Host "Attempt to get headers for $url failed.`n $($_.Exception.Message)" + } + } + + $needsDownload = $true + $fiCached = New-Object System.IO.FileInfo($fileFullPath) + if ($fiCached.Exists -and -not ($forceDownload)) { + if ($checksum -ne $null -and $checksum -ne '') { + try { + Write-Host "File appears to be downloaded already. Verifying with package checksum to determine if it needs to be redownloaded." + Get-ChecksumValid -file $fileFullPath -checkSum $checksum -checksumType $checksumType -originalUrl $url -ErrorAction "Stop" + $needsDownload = $false + } + catch { + Write-Debug "Existing file failed checksum. Will be redownloaded from url." + } + } + elseif ($headers.Count -ne 0 -and $headers.ContainsKey("Content-Length")) { + # if the file already exists there is no reason to download it again. + if ($fiCached.Length -eq $headers["Content-Length"]) { + $needsDownload = $false + } + } + } + + if ($needsDownload) { + Write-Host "Downloading $packageName $bitPackage from `'$url`'" - Get-WebFile -Url $url -FileName $fileFullPath -Options $options - } else { - Write-Debug "$($packageName)'s requested file has already been downloaded. Using cached copy at + Get-WebFile -Url $url -FileName $fileFullPath -Options $options + } + else { + Write-Debug "$($packageName)'s requested file has already been downloaded. Using cached copy at '$fileFullPath'." + } } - } elseif ($url.StartsWith('ftp')) { - Write-Host "Ftp-ing $packageName + elseif ($url.StartsWith('ftp')) { + Write-Host "Ftp-ing $packageName from '$url'" - Get-FtpFile -Url $url -FileName $fileFullPath - } else { - if ($url.StartsWith('file:')) { $url = ([uri] $url).LocalPath } - Write-Host "Copying $packageName + Get-FtpFile -Url $url -FileName $fileFullPath + } + else { + if ($url.StartsWith('file:')) { + $url = ([uri] $url).LocalPath + } + Write-Host "Copying $packageName from `'$url`'" - Copy-Item $url -Destination $fileFullPath -Force - $urlIsRemote = $false - } + Copy-Item $url -Destination $fileFullPath -Force + $urlIsRemote = $false + } - Start-Sleep 2 #give it a sec or two to finish up copying + Start-Sleep 2 #give it a sec or two to finish up copying - $fi = New-Object System.IO.FileInfo($fileFullPath) - # validate file exists - if (!($fi.Exists)) { throw "Chocolatey expected a file to be downloaded to `'$fileFullPath`' but nothing exists at that location." } + $fi = New-Object System.IO.FileInfo($fileFullPath) + # validate file exists + if (!($fi.Exists)) { + throw "Chocolatey expected a file to be downloaded to `'$fileFullPath`' but nothing exists at that location." + } - Get-VirusCheckValid -Location $url -File $fileFullPath + Get-VirusCheckValid -Location $url -File $fileFullPath - if ($headers.Count -ne 0 -and ($checksum -eq $null -or $checksum -eq '')) { - # validate length is what we expected - Write-Debug "Checking that '$fileFullPath' is the size we expect it to be." - if ($headers.ContainsKey("Content-Length") -and ($fi.Length -ne $headers["Content-Length"])) { throw "Chocolatey expected a file at '$fileFullPath' to be of length '$($headers["Content-Length"])' but the length was '$($fi.Length)'." } + if ($headers.Count -ne 0 -and ($checksum -eq $null -or $checksum -eq '')) { + # validate length is what we expected + Write-Debug "Checking that '$fileFullPath' is the size we expect it to be." + if ($headers.ContainsKey("Content-Length") -and ($fi.Length -ne $headers["Content-Length"])) { + throw "Chocolatey expected a file at '$fileFullPath' to be of length '$($headers["Content-Length"])' but the length was '$($fi.Length)'." + } - if ($headers.ContainsKey("X-Checksum-Sha1")) { - $remoteChecksum = $headers["X-Checksum-Sha1"] - Write-Debug "Verifying remote checksum of '$remoteChecksum' for '$fileFullPath'." - Get-ChecksumValid -File $fileFullPath -Checksum $remoteChecksum -ChecksumType 'sha1' -OriginalUrl $url + if ($headers.ContainsKey("X-Checksum-Sha1")) { + $remoteChecksum = $headers["X-Checksum-Sha1"] + Write-Debug "Verifying remote checksum of '$remoteChecksum' for '$fileFullPath'." + Get-ChecksumValid -File $fileFullPath -Checksum $remoteChecksum -ChecksumType 'sha1' -OriginalUrl $url + } } - } - #skip requirement for embedded files if checksum is not provided - if ($urlIsRemote -or ($checksum -ne $null -and $checksum -ne '')) { - Write-Debug "Verifying package provided checksum of '$checksum' for '$fileFullPath'." - Get-ChecksumValid -File $fileFullPath -Checksum $checksum -ChecksumType $checksumType -OriginalUrl $url - } + #skip requirement for embedded files if checksum is not provided + if ($urlIsRemote -or ($checksum -ne $null -and $checksum -ne '')) { + Write-Debug "Verifying package provided checksum of '$checksum' for '$fileFullPath'." + Get-ChecksumValid -File $fileFullPath -Checksum $checksum -ChecksumType $checksumType -OriginalUrl $url + } - return $fileFullPath + return $fileFullPath } diff --git a/src/chocolatey.resources/helpers/functions/Get-EnvironmentVariable.ps1 b/src/chocolatey.resources/helpers/functions/Get-EnvironmentVariable.ps1 index e99a4600bc..38ea6750a1 100644 --- a/src/chocolatey.resources/helpers/functions/Get-EnvironmentVariable.ps1 +++ b/src/chocolatey.resources/helpers/functions/Get-EnvironmentVariable.ps1 @@ -15,7 +15,7 @@ # limitations under the License. function Get-EnvironmentVariable { -<# + <# .SYNOPSIS Gets an Environment Variable. @@ -55,53 +55,56 @@ Get-EnvironmentVariableNames .LINK Set-EnvironmentVariable #> -[CmdletBinding()] -[OutputType([string])] -param( - [Parameter(Mandatory=$true)][string] $Name, - [Parameter(Mandatory=$true)][System.EnvironmentVariableTarget] $Scope, - [Parameter(Mandatory=$false)][switch] $PreserveVariables = $false, - [parameter(ValueFromRemainingArguments = $true)][Object[]] $ignoredArguments -) - - # Do not log function call, it may expose variable names - ## Called from chocolateysetup.psm1 - wrap any Write-Host in try/catch - - [string] $MACHINE_ENVIRONMENT_REGISTRY_KEY_NAME = "SYSTEM\CurrentControlSet\Control\Session Manager\Environment\"; - [Microsoft.Win32.RegistryKey] $win32RegistryKey = [Microsoft.Win32.Registry]::LocalMachine.OpenSubKey($MACHINE_ENVIRONMENT_REGISTRY_KEY_NAME) - if ($Scope -eq [System.EnvironmentVariableTarget]::User) { - [string] $USER_ENVIRONMENT_REGISTRY_KEY_NAME = "Environment"; - [Microsoft.Win32.RegistryKey] $win32RegistryKey = [Microsoft.Win32.Registry]::CurrentUser.OpenSubKey($USER_ENVIRONMENT_REGISTRY_KEY_NAME) - } elseif ($Scope -eq [System.EnvironmentVariableTarget]::Process) { - return [Environment]::GetEnvironmentVariable($Name, $Scope) - } - - [Microsoft.Win32.RegistryValueOptions] $registryValueOptions = [Microsoft.Win32.RegistryValueOptions]::None - - if ($PreserveVariables) { - Write-Verbose "Choosing not to expand environment names" - $registryValueOptions = [Microsoft.Win32.RegistryValueOptions]::DoNotExpandEnvironmentNames - } - - [string] $environmentVariableValue = [string]::Empty - - try { - #Write-Verbose "Getting environment variable $Name" - if ($win32RegistryKey -ne $null) { - # Some versions of Windows do not have HKCU:\Environment - $environmentVariableValue = $win32RegistryKey.GetValue($Name, [string]::Empty, $registryValueOptions) + [CmdletBinding()] + [OutputType([string])] + param( + [Parameter(Mandatory = $true)][string] $Name, + [Parameter(Mandatory = $true)][System.EnvironmentVariableTarget] $Scope, + [Parameter(Mandatory = $false)][switch] $PreserveVariables = $false, + [parameter(ValueFromRemainingArguments = $true)][Object[]] $ignoredArguments + ) + + # Do not log function call, it may expose variable names + ## Called from chocolateysetup.psm1 - wrap any Write-Host in try/catch + + [string] $MACHINE_ENVIRONMENT_REGISTRY_KEY_NAME = "SYSTEM\CurrentControlSet\Control\Session Manager\Environment\"; + [Microsoft.Win32.RegistryKey] $win32RegistryKey = [Microsoft.Win32.Registry]::LocalMachine.OpenSubKey($MACHINE_ENVIRONMENT_REGISTRY_KEY_NAME) + if ($Scope -eq [System.EnvironmentVariableTarget]::User) { + [string] $USER_ENVIRONMENT_REGISTRY_KEY_NAME = "Environment"; + [Microsoft.Win32.RegistryKey] $win32RegistryKey = [Microsoft.Win32.Registry]::CurrentUser.OpenSubKey($USER_ENVIRONMENT_REGISTRY_KEY_NAME) } - } catch { - Write-Debug "Unable to retrieve the $Name environment variable. Details: $_" - } finally { - if ($win32RegistryKey -ne $null) { - $win32RegistryKey.Close() + elseif ($Scope -eq [System.EnvironmentVariableTarget]::Process) { + return [Environment]::GetEnvironmentVariable($Name, $Scope) } - } - if ($environmentVariableValue -eq $null -or $environmentVariableValue -eq '') { - $environmentVariableValue = [Environment]::GetEnvironmentVariable($Name, $Scope) - } + [Microsoft.Win32.RegistryValueOptions] $registryValueOptions = [Microsoft.Win32.RegistryValueOptions]::None - return $environmentVariableValue + if ($PreserveVariables) { + Write-Verbose "Choosing not to expand environment names" + $registryValueOptions = [Microsoft.Win32.RegistryValueOptions]::DoNotExpandEnvironmentNames + } + + [string] $environmentVariableValue = [string]::Empty + + try { + #Write-Verbose "Getting environment variable $Name" + if ($win32RegistryKey -ne $null) { + # Some versions of Windows do not have HKCU:\Environment + $environmentVariableValue = $win32RegistryKey.GetValue($Name, [string]::Empty, $registryValueOptions) + } + } + catch { + Write-Debug "Unable to retrieve the $Name environment variable. Details: $_" + } + finally { + if ($win32RegistryKey -ne $null) { + $win32RegistryKey.Close() + } + } + + if ($environmentVariableValue -eq $null -or $environmentVariableValue -eq '') { + $environmentVariableValue = [Environment]::GetEnvironmentVariable($Name, $Scope) + } + + return $environmentVariableValue } diff --git a/src/chocolatey.resources/helpers/functions/Get-EnvironmentVariableNames.ps1 b/src/chocolatey.resources/helpers/functions/Get-EnvironmentVariableNames.ps1 index a66eb313eb..229c99ec61 100644 --- a/src/chocolatey.resources/helpers/functions/Get-EnvironmentVariableNames.ps1 +++ b/src/chocolatey.resources/helpers/functions/Get-EnvironmentVariableNames.ps1 @@ -15,7 +15,7 @@ # limitations under the License. function Get-EnvironmentVariableNames([System.EnvironmentVariableTarget] $Scope) { -<# + <# .SYNOPSIS Gets all environment variable names. @@ -47,13 +47,21 @@ Get-EnvironmentVariable Set-EnvironmentVariable #> - # Do not log function call + # Do not log function call - # HKCU:\Environment may not exist in all Windows OSes (such as Server Core). - switch ($Scope) { - 'User' { Get-Item 'HKCU:\Environment' -ErrorAction SilentlyContinue | Select-Object -ExpandProperty Property } - 'Machine' { Get-Item 'HKLM:\SYSTEM\CurrentControlSet\Control\Session Manager\Environment' | Select-Object -ExpandProperty Property } - 'Process' { Get-ChildItem Env:\ | Select-Object -ExpandProperty Key } - default { throw "Unsupported environment scope: $Scope" } - } + # HKCU:\Environment may not exist in all Windows OSes (such as Server Core). + switch ($Scope) { + 'User' { + Get-Item 'HKCU:\Environment' -ErrorAction SilentlyContinue | Select-Object -ExpandProperty Property + } + 'Machine' { + Get-Item 'HKLM:\SYSTEM\CurrentControlSet\Control\Session Manager\Environment' | Select-Object -ExpandProperty Property + } + 'Process' { + Get-ChildItem Env:\ | Select-Object -ExpandProperty Key + } + default { + throw "Unsupported environment scope: $Scope" + } + } } diff --git a/src/chocolatey.resources/helpers/functions/Get-FtpFile.ps1 b/src/chocolatey.resources/helpers/functions/Get-FtpFile.ps1 index 4906c1ce34..a48d632778 100644 --- a/src/chocolatey.resources/helpers/functions/Get-FtpFile.ps1 +++ b/src/chocolatey.resources/helpers/functions/Get-FtpFile.ps1 @@ -14,7 +14,7 @@ ## - Request / ReadWriteResponse Timeouts ############################################################################################################## function Get-FtpFile { -<# + <# .SYNOPSIS Downloads a file from a File Transfer Protocol (FTP) location. @@ -61,155 +61,174 @@ Get-ChocolateyWebFile .LINK Get-WebFile #> -param( - [parameter(Mandatory=$false, Position=0)][string] $url = '', - [parameter(Mandatory=$true, Position=1)][string] $fileName = $null, - [parameter(Mandatory=$false, Position=2)][string] $username = $null, - [parameter(Mandatory=$false, Position=3)][string] $password = $null, - [parameter(Mandatory=$false)][switch] $quiet, - [parameter(ValueFromRemainingArguments = $true)][Object[]] $ignoredArguments -) - - Write-FunctionCallLogMessage -Invocation $MyInvocation -Parameters $PSBoundParameters - - if ($url -eq $null -or $url -eq '') { - Write-Warning "Url parameter is empty, Get-FtpFile has nothing to do." - return - } - - if ($fileName -eq $null -or $fileName -eq '') { - Write-Warning "FileName parameter is empty, Get-FtpFile cannot save the output." - return - } - - try { - $uri = [System.Uri]$url - if ($uri.IsFile()) { - Write-Debug "Url is local file, setting destination" - if ($url.LocalPath -ne $fileName) { - Copy-Item $uri.LocalPath -Destination $fileName -Force - } - - return + param( + [parameter(Mandatory = $false, Position = 0)][string] $url = '', + [parameter(Mandatory = $true, Position = 1)][string] $fileName = $null, + [parameter(Mandatory = $false, Position = 2)][string] $username = $null, + [parameter(Mandatory = $false, Position = 3)][string] $password = $null, + [parameter(Mandatory = $false)][switch] $quiet, + [parameter(ValueFromRemainingArguments = $true)][Object[]] $ignoredArguments + ) + + Write-FunctionCallLogMessage -Invocation $MyInvocation -Parameters $PSBoundParameters + + if ($url -eq $null -or $url -eq '') { + Write-Warning "Url parameter is empty, Get-FtpFile has nothing to do." + return } - } catch { - #continue on - } - - # Create a FTPWebRequest object to handle the connection to the ftp server - $ftprequest = [System.Net.FtpWebRequest]::create($url) - - # check if a proxy is required - $explicitProxy = $env:chocolateyProxyLocation - $explicitProxyUser = $env:chocolateyProxyUser - $explicitProxyPassword = $env:chocolateyProxyPassword - $explicitProxyBypassList = $env:chocolateyProxyBypassList - $explicitProxyBypassOnLocal = $env:chocolateyProxyBypassOnLocal - if ($explicitProxy -ne $null) { - # explicit proxy - $proxy = New-Object System.Net.WebProxy($explicitProxy, $true) - if ($explicitProxyPassword -ne $null) { - $passwd = ConvertTo-SecureString $explicitProxyPassword -AsPlainText -Force - $proxy.Credentials = New-Object System.Management.Automation.PSCredential ($explicitProxyUser, $passwd) - } - - if ($explicitProxyBypassList -ne $null -and $explicitProxyBypassList -ne '') { - $proxy.BypassList = $explicitProxyBypassList.Split(',', [System.StringSplitOptions]::RemoveEmptyEntries) + + if ($fileName -eq $null -or $fileName -eq '') { + Write-Warning "FileName parameter is empty, Get-FtpFile cannot save the output." + return } - if ($explicitProxyBypassOnLocal -eq 'true') { $proxy.BypassProxyOnLocal = $true; } - - Write-Host "Using explicit proxy server '$explicitProxy'." - $ftprequest.Proxy = $proxy - } - - # set the request's network credentials for an authenticated connection - $ftprequest.Credentials = New-Object System.Net.NetworkCredential($username, $password) - - $ftprequest.Method = [System.Net.WebRequestMethods+Ftp]::DownloadFile - $ftprequest.UseBinary = $true - $ftprequest.KeepAlive = $false - - # use the default request timeout of 100000 - if ($env:chocolateyRequestTimeout -ne $null -and $env:chocolateyRequestTimeout -ne '') { - $ftprequest.Timeout = $env:chocolateyRequestTimeout - } - if ($env:chocolateyResponseTimeout -ne $null -and $env:chocolateyResponseTimeout -ne '') { - $ftprequest.ReadWriteTimeout = $env:chocolateyResponseTimeout - } - - try { - # send the ftp request to the server - $ftpresponse = $ftprequest.GetResponse() - [long]$goal = $ftpresponse.ContentLength - $goalFormatted = Format-FileSize $goal - - # get a download stream from the server response - $reader = $ftpresponse.GetResponseStream() - - # create the target file on the local system and the download buffer - $writer = New-Object IO.FileStream ($fileName,[IO.FileMode]::Create) - [byte[]]$buffer = New-Object byte[] 1048576 - [long]$total = [long]$count = 0 - - $originalEAP = $ErrorActionPreference - $ErrorActionPreference = 'Stop' + try { - # loop through the download stream and send the data to the target file - do { - $count = $reader.Read($buffer, 0, $buffer.Length); - $writer.Write($buffer, 0, $count); - if(!$quiet) { - $total += $count - $totalFormatted = Format-FileSize $total - if($goal -gt 0) { - $percentComplete = [Math]::Truncate(($total/$goal)*100) - Write-Progress "Downloading $url to $fileName" "Saving $totalFormatted of $goalFormatted ($total/$goal)" -id 0 -percentComplete $percentComplete - } else { - Write-Progress "Downloading $url to $fileName" "Saving $total bytes..." -id 0 -Completed - } - if ($total -eq $goal -and $count -eq 0) { - Write-Progress "Completed download of $url." "Completed a total of $total bytes of $fileName" -id 0 -Completed -PercentComplete 100 - } + $uri = [System.Uri]$url + if ($uri.IsFile()) { + Write-Debug "Url is local file, setting destination" + if ($url.LocalPath -ne $fileName) { + Copy-Item $uri.LocalPath -Destination $fileName -Force + } + + return } - } while ($count -ne 0) - Write-Host "" - Write-Host "Download of $([System.IO.Path]::GetFileName($fileName)) ($goalFormatted) completed." - } finally { - $ErrorActionPreference = $originalEAP + } + catch { + #continue on } - $writer.Flush() # closed in finally block + # Create a FTPWebRequest object to handle the connection to the ftp server + $ftprequest = [System.Net.FtpWebRequest]::create($url) + + # check if a proxy is required + $explicitProxy = $env:chocolateyProxyLocation + $explicitProxyUser = $env:chocolateyProxyUser + $explicitProxyPassword = $env:chocolateyProxyPassword + $explicitProxyBypassList = $env:chocolateyProxyBypassList + $explicitProxyBypassOnLocal = $env:chocolateyProxyBypassOnLocal + if ($explicitProxy -ne $null) { + # explicit proxy + $proxy = New-Object System.Net.WebProxy($explicitProxy, $true) + if ($explicitProxyPassword -ne $null) { + $passwd = ConvertTo-SecureString $explicitProxyPassword -AsPlainText -Force + $proxy.Credentials = New-Object System.Management.Automation.PSCredential ($explicitProxyUser, $passwd) + } - } catch { - if ($ftprequest -ne $null) { - $ftprequest.ServicePoint.MaxIdleTime = 0 - $ftprequest.Abort(); - # ruthlessly remove $ftprequest to ensure it isn't reused - Remove-Variable ftprequest - Start-Sleep 1 - [GC]::Collect() - } + if ($explicitProxyBypassList -ne $null -and $explicitProxyBypassList -ne '') { + $proxy.BypassList = $explicitProxyBypassList.Split(',', [System.StringSplitOptions]::RemoveEmptyEntries) + } + if ($explicitProxyBypassOnLocal -eq 'true') { + $proxy.BypassProxyOnLocal = $true; + } - Set-PowerShellExitCode 404 - if ($env:DownloadCacheAvailable -eq 'true') { - throw "The remote file either doesn't exist, is unauthorized, or is forbidden for url '$url'. $($_.Exception.Message) `nThis package is likely not broken for licensed users - see https://docs.chocolatey.org/en-us/features/private-cdn." - } else { - throw "The remote file either doesn't exist, is unauthorized, or is forbidden for url '$url'. $($_.Exception.Message)" + Write-Host "Using explicit proxy server '$explicitProxy'." + $ftprequest.Proxy = $proxy } - } finally { - if ($reader -ne $null) { - try { $reader.Close(); } catch {} + # set the request's network credentials for an authenticated connection + $ftprequest.Credentials = New-Object System.Net.NetworkCredential($username, $password) + + $ftprequest.Method = [System.Net.WebRequestMethods+Ftp]::DownloadFile + $ftprequest.UseBinary = $true + $ftprequest.KeepAlive = $false + + # use the default request timeout of 100000 + if ($env:chocolateyRequestTimeout -ne $null -and $env:chocolateyRequestTimeout -ne '') { + $ftprequest.Timeout = $env:chocolateyRequestTimeout + } + if ($env:chocolateyResponseTimeout -ne $null -and $env:chocolateyResponseTimeout -ne '') { + $ftprequest.ReadWriteTimeout = $env:chocolateyResponseTimeout } - if ($writer -ne $null) { - try { $writer.Close(); } catch {} + try { + # send the ftp request to the server + $ftpresponse = $ftprequest.GetResponse() + [long]$goal = $ftpresponse.ContentLength + $goalFormatted = Format-FileSize $goal + + # get a download stream from the server response + $reader = $ftpresponse.GetResponseStream() + + # create the target file on the local system and the download buffer + $writer = New-Object IO.FileStream ($fileName, [IO.FileMode]::Create) + [byte[]]$buffer = New-Object byte[] 1048576 + [long]$total = [long]$count = 0 + + $originalEAP = $ErrorActionPreference + $ErrorActionPreference = 'Stop' + try { + # loop through the download stream and send the data to the target file + do { + $count = $reader.Read($buffer, 0, $buffer.Length); + $writer.Write($buffer, 0, $count); + if (!$quiet) { + $total += $count + $totalFormatted = Format-FileSize $total + if ($goal -gt 0) { + $percentComplete = [Math]::Truncate(($total / $goal) * 100) + Write-Progress "Downloading $url to $fileName" "Saving $totalFormatted of $goalFormatted ($total/$goal)" -Id 0 -PercentComplete $percentComplete + } + else { + Write-Progress "Downloading $url to $fileName" "Saving $total bytes..." -Id 0 -Completed + } + if ($total -eq $goal -and $count -eq 0) { + Write-Progress "Completed download of $url." "Completed a total of $total bytes of $fileName" -Id 0 -Completed -PercentComplete 100 + } + } + } while ($count -ne 0) + Write-Host "" + Write-Host "Download of $([System.IO.Path]::GetFileName($fileName)) ($goalFormatted) completed." + } + finally { + $ErrorActionPreference = $originalEAP + } + + $writer.Flush() # closed in finally block } + catch { + if ($ftprequest -ne $null) { + $ftprequest.ServicePoint.MaxIdleTime = 0 + $ftprequest.Abort(); + # ruthlessly remove $ftprequest to ensure it isn't reused + Remove-Variable ftprequest + Start-Sleep 1 + [GC]::Collect() + } - if ($ftpresponse -ne $null) { - try { $ftpresponse.Close(); } catch {} + Set-PowerShellExitCode 404 + if ($env:DownloadCacheAvailable -eq 'true') { + throw "The remote file either doesn't exist, is unauthorized, or is forbidden for url '$url'. $($_.Exception.Message) `nThis package is likely not broken for licensed users - see https://docs.chocolatey.org/en-us/features/private-cdn." + } + else { + throw "The remote file either doesn't exist, is unauthorized, or is forbidden for url '$url'. $($_.Exception.Message)" + } } + finally { + + if ($reader -ne $null) { + try { + $reader.Close(); + } + catch { + } + } - Start-Sleep 1 - } + if ($writer -ne $null) { + try { + $writer.Close(); + } + catch { + } + } + + if ($ftpresponse -ne $null) { + try { + $ftpresponse.Close(); + } + catch { + } + } + + Start-Sleep 1 + } } diff --git a/src/chocolatey.resources/helpers/functions/Get-OSArchitectureWidth.ps1 b/src/chocolatey.resources/helpers/functions/Get-OSArchitectureWidth.ps1 index eee31cecb2..1f7097c2a1 100644 --- a/src/chocolatey.resources/helpers/functions/Get-OSArchitectureWidth.ps1 +++ b/src/chocolatey.resources/helpers/functions/Get-OSArchitectureWidth.ps1 @@ -15,7 +15,7 @@ # limitations under the License. function Get-OSArchitectureWidth { -<# + <# .SYNOPSIS Get the operating system architecture address width. @@ -46,40 +46,43 @@ None This optional parameter causes the function to return $true or $false, depending on whether or not the bit width matches. #> -param( - $compare -) + param( + $compare + ) - Write-FunctionCallLogMessage -Invocation $MyInvocation -Parameters $PSBoundParameters + Write-FunctionCallLogMessage -Invocation $MyInvocation -Parameters $PSBoundParameters - $bits = 64 - if (([System.IntPtr]::Size -eq 4) -and (Test-Path env:\PROCESSOR_ARCHITEW6432)) { $bits = 64 - } elseif ([System.IntPtr]::Size -eq 4) { - $bits = 32 - } + if (([System.IntPtr]::Size -eq 4) -and (Test-Path env:\PROCESSOR_ARCHITEW6432)) { + $bits = 64 + } + elseif ([System.IntPtr]::Size -eq 4) { + $bits = 32 + } - # ARM64 has a x86 32bit emulator, so we need to select 32 bit if we detect - # ARM64 - According to Microsoft on 2019 APR 18 (jkunkee), there are no - # current plans to ship 64-bit emulation for ARM64. - $processorArchitecture = $env:PROCESSOR_ARCHITECTURE - if ($processorArchitecture -and $processorArchitecture -eq 'ARM64') { - $bits = 32 - } + # ARM64 has a x86 32bit emulator, so we need to select 32 bit if we detect + # ARM64 - According to Microsoft on 2019 APR 18 (jkunkee), there are no + # current plans to ship 64-bit emulation for ARM64. + $processorArchitecture = $env:PROCESSOR_ARCHITECTURE + if ($processorArchitecture -and $processorArchitecture -eq 'ARM64') { + $bits = 32 + } - $processorArchiteW6432 = $env:PROCESSOR_ARCHITEW6432 - if ($processorArchiteW6432 -and $processorArchiteW6432 -eq 'ARM64') { - $bits = 32 - } + $processorArchiteW6432 = $env:PROCESSOR_ARCHITEW6432 + if ($processorArchiteW6432 -and $processorArchiteW6432 -eq 'ARM64') { + $bits = 32 + } - # Return bool|int - if ("$compare" -ne '' -and $compare -eq $bits) { - return $true - } elseif ("$compare" -ne '') { - return $false - } else { - return $bits - } + # Return bool|int + if ("$compare" -ne '' -and $compare -eq $bits) { + return $true + } + elseif ("$compare" -ne '') { + return $false + } + else { + return $bits + } } Set-Alias Get-ProcessorBits Get-OSArchitectureWidth diff --git a/src/chocolatey.resources/helpers/functions/Get-PackageParameters.ps1 b/src/chocolatey.resources/helpers/functions/Get-PackageParameters.ps1 index 2c5222bfb6..29bcf11804 100644 --- a/src/chocolatey.resources/helpers/functions/Get-PackageParameters.ps1 +++ b/src/chocolatey.resources/helpers/functions/Get-PackageParameters.ps1 @@ -21,7 +21,7 @@ # used. However nearly all of the code is a different implementation. function Get-PackageParameters { -<# + <# .SYNOPSIS Parses a string and returns a hash table array of those values for use in package scripts. @@ -122,46 +122,54 @@ Install-ChocolateyInstallPackage .LINK Install-ChocolateyZipPackage #> -param( - [parameter(Mandatory=$false, Position=0)] - [alias("params")][string] $parameters = '', - [parameter(ValueFromRemainingArguments = $true)][Object[]] $ignoredArguments -) - - Write-FunctionCallLogMessage -Invocation $MyInvocation -Parameters $PSBoundParameters - - $useDefaultParameters = $false - $loggingAllowed = $true - $paramStrings = @($parameters) - - if (!$parameters -or $parameters -eq '') { - $useDefaultParameters = $true - # if we are using default parameters, we are going to loop over two items - Write-Debug 'Parsing $env:ChocolateyPackageParameters and $env:ChocolateyPackageParametersSensitive for parameters' - $paramStrings = @("$env:ChocolateyPackageParameters","$env:ChocolateyPackageParametersSensitive") - if ($env:ChocolateyPackageParametersSensitive) { - Write-Debug "Sensitive parameters detected, no logging of parameters." - $loggingAllowed = $false + param( + [parameter(Mandatory = $false, Position = 0)] + [alias("params")][string] $parameters = '', + [parameter(ValueFromRemainingArguments = $true)][Object[]] $ignoredArguments + ) + + Write-FunctionCallLogMessage -Invocation $MyInvocation -Parameters $PSBoundParameters + + $useDefaultParameters = $false + $loggingAllowed = $true + $paramStrings = @($parameters) + + if (!$parameters -or $parameters -eq '') { + $useDefaultParameters = $true + # if we are using default parameters, we are going to loop over two items + Write-Debug 'Parsing $env:ChocolateyPackageParameters and $env:ChocolateyPackageParametersSensitive for parameters' + $paramStrings = @("$env:ChocolateyPackageParameters", "$env:ChocolateyPackageParametersSensitive") + if ($env:ChocolateyPackageParametersSensitive) { + Write-Debug "Sensitive parameters detected, no logging of parameters." + $loggingAllowed = $false + } } - } - $paramHash = @{} - - foreach ($paramString in $paramStrings) { - if (!$paramString -or $paramString -eq '') { continue } - - Select-String '(?:^|\s+)\/(?[^\:\=\s)]+)(?:(?:\:|=){1}(?:\''|\"){0,1}(?.*?)(?:\''|\"){0,1}(?:(?=\s+\/)|$))?' -Input $paramString -AllMatches | ForEach-Object { $_.Matches } | ForEach-Object { - if (!$_) { continue } #Posh v2 issue? - $paramItemName = ($_.Groups["ItemKey"].Value).Trim() - $paramItemValue = ($_.Groups["ItemValue"].Value).Trim() - if (!$paramItemValue -or $paramItemValue -eq '') { $paramItemValue = $true } - - if ($loggingAllowed) { Write-Debug "Adding package param '$paramItemName'='$paramItemValue'" } - $paramHash[$paramItemName] = $paramItemValue + $paramHash = @{} + + foreach ($paramString in $paramStrings) { + if (!$paramString -or $paramString -eq '') { + continue + } + + Select-String '(?:^|\s+)\/(?[^\:\=\s)]+)(?:(?:\:|=){1}(?:\''|\"){0,1}(?.*?)(?:\''|\"){0,1}(?:(?=\s+\/)|$))?' -Input $paramString -AllMatches | ForEach-Object { $_.Matches } | ForEach-Object { + if (!$_) { + continue + } #Posh v2 issue? + $paramItemName = ($_.Groups["ItemKey"].Value).Trim() + $paramItemValue = ($_.Groups["ItemValue"].Value).Trim() + if (!$paramItemValue -or $paramItemValue -eq '') { + $paramItemValue = $true + } + + if ($loggingAllowed) { + Write-Debug "Adding package param '$paramItemName'='$paramItemValue'" + } + $paramHash[$paramItemName] = $paramItemValue + } } - } - $paramHash + $paramHash } # override Get-PackageParameters in chocolatey-core.extension package diff --git a/src/chocolatey.resources/helpers/functions/Get-ToolsLocation.ps1 b/src/chocolatey.resources/helpers/functions/Get-ToolsLocation.ps1 index e6260f37f0..dadefd6ac5 100644 --- a/src/chocolatey.resources/helpers/functions/Get-ToolsLocation.ps1 +++ b/src/chocolatey.resources/helpers/functions/Get-ToolsLocation.ps1 @@ -14,7 +14,7 @@ # limitations under the License. function Get-ToolsLocation { -<# + <# .SYNOPSIS Gets the top level location for tools/software installed outside of package folders. @@ -45,53 +45,56 @@ None None #> - $invocation = $MyInvocation - Write-FunctionCallLogMessage -Invocation $invocation -Parameters $PSBoundParameters + $invocation = $MyInvocation + Write-FunctionCallLogMessage -Invocation $invocation -Parameters $PSBoundParameters - if ($invocation -ne $null -and $invocation.InvocationName -ne $null -and $invocation.InvocationName.ToLower() -eq 'get-binroot') { - Write-Warning "Get-BinRoot was deprecated in v1 and will be removed in v2. It has been replaced with Get-ToolsLocation (starting with v0.9.10), however many packages no longer require a special separate directory since package folders no longer have versions on them. Some do though and should continue to use Get-ToolsLocation." - } + if ($invocation -ne $null -and $invocation.InvocationName -ne $null -and $invocation.InvocationName.ToLower() -eq 'get-binroot') { + Write-Warning "Get-BinRoot was deprecated in v1 and will be removed in v2. It has been replaced with Get-ToolsLocation (starting with v0.9.10), however many packages no longer require a special separate directory since package folders no longer have versions on them. Some do though and should continue to use Get-ToolsLocation." + } - $toolsLocation = $env:ChocolateyToolsLocation + $toolsLocation = $env:ChocolateyToolsLocation - if ($toolsLocation -eq $null) { - $binRoot = $env:ChocolateyBinRoot - $olderRoot = $env:chocolatey_bin_root + if ($toolsLocation -eq $null) { + $binRoot = $env:ChocolateyBinRoot + $olderRoot = $env:chocolatey_bin_root - if ($binRoot -eq $null -and $olderRoot -eq $null) { - $toolsLocation = Join-Path $env:systemdrive 'tools' - } else { - if ($olderRoot -ne $null) { - if ($binRoot -eq $null) { - $binRoot = $olderRoot + if ($binRoot -eq $null -and $olderRoot -eq $null) { + $toolsLocation = Join-Path $env:systemdrive 'tools' + } + else { + if ($olderRoot -ne $null) { + if ($binRoot -eq $null) { + $binRoot = $olderRoot + } + Set-EnvironmentVariable -Name "chocolatey_bin_root" -Value '' -Scope User -ErrorAction SilentlyContinue + } + + $toolsLocation = $binRoot + Set-EnvironmentVariable -Name "ChocolateyBinRoot" -Value '' -Scope User -ErrorAction SilentlyContinue } - Set-EnvironmentVariable -Name "chocolatey_bin_root" -Value '' -Scope User -ErrorAction SilentlyContinue - } + } - $toolsLocation = $binRoot - Set-EnvironmentVariable -Name "ChocolateyBinRoot" -Value '' -Scope User -ErrorAction SilentlyContinue + # Add a drive letter if one doesn't exist + if (-not($toolsLocation -imatch "^\w:")) { + $toolsLocation = Join-Path $env:systemdrive $toolsLocation } - } - - # Add a drive letter if one doesn't exist - if (-not($toolsLocation -imatch "^\w:")) { - $toolsLocation = Join-Path $env:systemdrive $toolsLocation - } - - if (-not($env:ChocolateyToolsLocation -eq $toolsLocation)) { - try { - Set-EnvironmentVariable -Name "ChocolateyToolsLocation" -Value $toolsLocation -Scope User - } catch { - if (Test-ProcessAdminRights) { - # sometimes User scope may not exist (such as with core) - Set-EnvironmentVariable -Name "ChocolateyToolsLocation" -Value $toolsLocation -Scope Machine - } else { - throw $_.Exception - } + + if (-not($env:ChocolateyToolsLocation -eq $toolsLocation)) { + try { + Set-EnvironmentVariable -Name "ChocolateyToolsLocation" -Value $toolsLocation -Scope User + } + catch { + if (Test-ProcessAdminRights) { + # sometimes User scope may not exist (such as with core) + Set-EnvironmentVariable -Name "ChocolateyToolsLocation" -Value $toolsLocation -Scope Machine + } + else { + throw $_.Exception + } + } } - } - return $toolsLocation + return $toolsLocation } Set-Alias Get-BinRoot Get-ToolsLocation -Force -Scope Global -Option AllScope diff --git a/src/chocolatey.resources/helpers/functions/Get-UACEnabled.ps1 b/src/chocolatey.resources/helpers/functions/Get-UACEnabled.ps1 index 9e6a23a140..c6ee50bcaf 100644 --- a/src/chocolatey.resources/helpers/functions/Get-UACEnabled.ps1 +++ b/src/chocolatey.resources/helpers/functions/Get-UACEnabled.ps1 @@ -15,7 +15,7 @@ # limitations under the License. function Get-UACEnabled { -<# + <# .SYNOPSIS Determines if UAC (User Account Control) is turned on or off. @@ -34,27 +34,26 @@ None System.Boolean #> - Write-FunctionCallLogMessage -Invocation $MyInvocation -Parameters $PSBoundParameters - - $uacRegPath = "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System" - $uacRegValue = "EnableLUA" - $uacEnabled = $false - - # http://msdn.microsoft.com/en-us/library/windows/desktop/ms724832(v=vs.85).aspx - $osVersion = [Environment]::OSVersion.Version - if ($osVersion -ge [Version]'6.0') - { - $uacRegSetting = Get-ItemProperty -Path $uacRegPath - try { - $uacValue = $uacRegSetting.EnableLUA - if ($uacValue -eq 1) { - $uacEnabled = $true - } - } catch { - #regkey doesn't exist, so proceed with false - + Write-FunctionCallLogMessage -Invocation $MyInvocation -Parameters $PSBoundParameters + + $uacRegPath = "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System" + $uacRegValue = "EnableLUA" + $uacEnabled = $false + + # http://msdn.microsoft.com/en-us/library/windows/desktop/ms724832(v=vs.85).aspx + $osVersion = [Environment]::OSVersion.Version + if ($osVersion -ge [Version]'6.0') { + $uacRegSetting = Get-ItemProperty -Path $uacRegPath + try { + $uacValue = $uacRegSetting.EnableLUA + if ($uacValue -eq 1) { + $uacEnabled = $true + } + } + catch { + #regkey doesn't exist, so proceed with false + } } - } - return $uacEnabled + return $uacEnabled } diff --git a/src/chocolatey.resources/helpers/functions/Get-UninstallRegistryKey.ps1 b/src/chocolatey.resources/helpers/functions/Get-UninstallRegistryKey.ps1 index a03ad69884..f48accff39 100644 --- a/src/chocolatey.resources/helpers/functions/Get-UninstallRegistryKey.ps1 +++ b/src/chocolatey.resources/helpers/functions/Get-UninstallRegistryKey.ps1 @@ -15,7 +15,7 @@ # limitations under the License. function Get-UninstallRegistryKey { -<# + <# .SYNOPSIS Retrieve registry key(s) for system-installed applications from an exact or wildcard search. @@ -105,65 +105,69 @@ Install-ChocolateyInstallPackage .LINK Uninstall-ChocolateyPackage #> -[CmdletBinding()] -param( - [parameter(Mandatory=$true, Position=0, ValueFromPipeline=$true)] - [string] $softwareName, - [parameter(ValueFromRemainingArguments = $true)][Object[]] $ignoredArguments -) - - Write-FunctionCallLogMessage -Invocation $MyInvocation -Parameters $PSBoundParameters - - if ($softwareName -eq $null -or $softwareName -eq '') { - throw "$SoftwareName cannot be empty for Get-UninstallRegistryKey" - } - - $ErrorActionPreference = 'Stop' - $local_key = 'HKCU:\Software\Microsoft\Windows\CurrentVersion\Uninstall\*' - $machine_key = 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\*' - $machine_key6432 = 'HKLM:\SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\*' - - Write-Verbose "Retrieving all uninstall registry keys" - [array]$keys = Get-ChildItem -Path @($machine_key6432, $machine_key, $local_key) -ErrorAction SilentlyContinue - Write-Debug "Registry uninstall keys on system: $($keys.Count)" - - Write-Debug "Error handling check: `'Get-ItemProperty`' fails if a registry key is encoded incorrectly." - [int]$maxAttempts = $keys.Count - for ([int]$attempt = 1; $attempt -le $maxAttempts; $attempt++) { - [bool]$success = $false - - $keyPaths = $keys | Select-Object -ExpandProperty PSPath - try { - [array]$foundKey = Get-ItemProperty -LiteralPath $keyPaths -ErrorAction Stop | Where-Object { $_.DisplayName -like $softwareName } - $success = $true - } catch { - Write-Debug "Found bad key." - foreach ($key in $keys){ + [CmdletBinding()] + param( + [parameter(Mandatory = $true, Position = 0, ValueFromPipeline = $true)] + [string] $softwareName, + [parameter(ValueFromRemainingArguments = $true)][Object[]] $ignoredArguments + ) + + Write-FunctionCallLogMessage -Invocation $MyInvocation -Parameters $PSBoundParameters + + if ($softwareName -eq $null -or $softwareName -eq '') { + throw "$SoftwareName cannot be empty for Get-UninstallRegistryKey" + } + + $ErrorActionPreference = 'Stop' + $local_key = 'HKCU:\Software\Microsoft\Windows\CurrentVersion\Uninstall\*' + $machine_key = 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\*' + $machine_key6432 = 'HKLM:\SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\*' + + Write-Verbose "Retrieving all uninstall registry keys" + [array]$keys = Get-ChildItem -Path @($machine_key6432, $machine_key, $local_key) -ErrorAction SilentlyContinue + Write-Debug "Registry uninstall keys on system: $($keys.Count)" + + Write-Debug "Error handling check: `'Get-ItemProperty`' fails if a registry key is encoded incorrectly." + [int]$maxAttempts = $keys.Count + for ([int]$attempt = 1; $attempt -le $maxAttempts; $attempt++) { + [bool]$success = $false + + $keyPaths = $keys | Select-Object -ExpandProperty PSPath try { - Get-ItemProperty -LiteralPath $key.PsPath > $null - } catch { - $badKey = $key.PsPath + [array]$foundKey = Get-ItemProperty -LiteralPath $keyPaths -ErrorAction Stop | Where-Object { $_.DisplayName -like $softwareName } + $success = $true + } + catch { + Write-Debug "Found bad key." + foreach ($key in $keys) { + try { + Get-ItemProperty -LiteralPath $key.PsPath > $null + } + catch { + $badKey = $key.PsPath + } + } + Write-Verbose "Skipping bad key: $badKey" + [array]$keys = $keys | Where-Object { $badKey -NotContains $_.PsPath } } - } - Write-Verbose "Skipping bad key: $badKey" - [array]$keys = $keys | Where-Object { $badKey -NotContains $_.PsPath } - } - if ($success) { break; } + if ($success) { + break; + } - if ($attempt -ge 10) { - Write-Warning "Found 10 or more bad registry keys. Run command again with `'--verbose --debug`' for more info." - Write-Debug "Each key searched should correspond to an installed program. It is very unlikely to have more than a few programs with incorrectly encoded keys, if any at all. This may be indicative of one or more corrupted registry branches." + if ($attempt -ge 10) { + Write-Warning "Found 10 or more bad registry keys. Run command again with `'--verbose --debug`' for more info." + Write-Debug "Each key searched should correspond to an installed program. It is very unlikely to have more than a few programs with incorrectly encoded keys, if any at all. This may be indicative of one or more corrupted registry branches." + } } - } - if ($foundKey -eq $null -or $foundkey.Count -eq 0) { - Write-Warning "No registry key found based on '$softwareName'" - } + if ($foundKey -eq $null -or $foundkey.Count -eq 0) { + Write-Warning "No registry key found based on '$softwareName'" + } - Write-Debug "Found $($foundKey.Count) uninstall registry key(s) with SoftwareName:`'$SoftwareName`'"; + Write-Debug "Found $($foundKey.Count) uninstall registry key(s) with SoftwareName:`'$SoftwareName`'"; - return $foundKey + return $foundKey } Set-Alias Get-InstallRegistryKey Get-UninstallRegistryKey diff --git a/src/chocolatey.resources/helpers/functions/Get-VirusCheckValid.ps1 b/src/chocolatey.resources/helpers/functions/Get-VirusCheckValid.ps1 index 880bee449b..753e786864 100644 --- a/src/chocolatey.resources/helpers/functions/Get-VirusCheckValid.ps1 +++ b/src/chocolatey.resources/helpers/functions/Get-VirusCheckValid.ps1 @@ -15,7 +15,7 @@ # limitations under the License. function Get-VirusCheckValid { -<# + <# .SYNOPSIS Used in Pro/Business editions. Runtime virus check against downloaded resources. @@ -43,10 +43,10 @@ The full file path to the file to verify against anti-virus scanners. .PARAMETER IgnoredArguments Allows splatting with arguments that do not apply. Do not use directly. #> -param( - [parameter(Mandatory=$false, Position=0)][string] $url, - [parameter(Mandatory=$false, Position=1)][string] $file = '', - [parameter(ValueFromRemainingArguments = $true)][Object[]] $ignoredArguments -) - Write-Debug "No runtime virus checking built into FOSS Chocolatey. Check out Pro/Business - https://chocolatey.org/compare" + param( + [parameter(Mandatory = $false, Position = 0)][string] $url, + [parameter(Mandatory = $false, Position = 1)][string] $file = '', + [parameter(ValueFromRemainingArguments = $true)][Object[]] $ignoredArguments + ) + Write-Debug "No runtime virus checking built into FOSS Chocolatey. Check out Pro/Business - https://chocolatey.org/compare" } diff --git a/src/chocolatey.resources/helpers/functions/Get-WebFile.ps1 b/src/chocolatey.resources/helpers/functions/Get-WebFile.ps1 index 23c778e164..df56a7c97d 100644 --- a/src/chocolatey.resources/helpers/functions/Get-WebFile.ps1 +++ b/src/chocolatey.resources/helpers/functions/Get-WebFile.ps1 @@ -23,7 +23,7 @@ ## - Request / ReadWriteResponse Timeouts ############################################################################################################## function Get-WebFile { -<# + <# .SYNOPSIS Downloads a file from an HTTP/HTTPS location. Prefer HTTPS when available. @@ -81,261 +81,283 @@ Get-WebHeaders .LINK Get-WebFileName #> -param( - [parameter(Mandatory=$false, Position=0)][string] $url = '', #(Read-Host "The URL to download"), - [parameter(Mandatory=$false, Position=1)][string] $fileName = $null, - [parameter(Mandatory=$false, Position=2)][string] $userAgent = 'chocolatey command line', - [parameter(Mandatory=$false)][switch] $Passthru, - [parameter(Mandatory=$false)][switch] $quiet, - [parameter(Mandatory=$false)][hashtable] $options = @{Headers=@{}}, - [parameter(ValueFromRemainingArguments = $true)][Object[]] $ignoredArguments -) - - Write-FunctionCallLogMessage -Invocation $MyInvocation -Parameters $PSBoundParameters - - try { - $uri = [System.Uri]$url - if ($uri.IsFile()) { - Write-Debug "Url is local file, setting destination" - if ($url.LocalPath -ne $fileName) { - Copy-Item $uri.LocalPath -Destination $fileName -Force - } - - return + param( + [parameter(Mandatory = $false, Position = 0)][string] $url = '', #(Read-Host "The URL to download"), + [parameter(Mandatory = $false, Position = 1)][string] $fileName = $null, + [parameter(Mandatory = $false, Position = 2)][string] $userAgent = 'chocolatey command line', + [parameter(Mandatory = $false)][switch] $Passthru, + [parameter(Mandatory = $false)][switch] $quiet, + [parameter(Mandatory = $false)][hashtable] $options = @{Headers = @{} }, + [parameter(ValueFromRemainingArguments = $true)][Object[]] $ignoredArguments + ) + + Write-FunctionCallLogMessage -Invocation $MyInvocation -Parameters $PSBoundParameters + + try { + $uri = [System.Uri]$url + if ($uri.IsFile()) { + Write-Debug "Url is local file, setting destination" + if ($url.LocalPath -ne $fileName) { + Copy-Item $uri.LocalPath -Destination $fileName -Force + } + + return + } } - } catch { - #continue on - } - - $req = [System.Net.HttpWebRequest]::Create($url); - $defaultCreds = [System.Net.CredentialCache]::DefaultCredentials - if ($defaultCreds -ne $null) { - $req.Credentials = $defaultCreds - } - - $webclient = new-object System.Net.WebClient - if ($defaultCreds -ne $null) { - $webClient.Credentials = $defaultCreds - } - - # check if a proxy is required - $explicitProxy = $env:chocolateyProxyLocation - $explicitProxyUser = $env:chocolateyProxyUser - $explicitProxyPassword = $env:chocolateyProxyPassword - $explicitProxyBypassList = $env:chocolateyProxyBypassList - $explicitProxyBypassOnLocal = $env:chocolateyProxyBypassOnLocal - if ($explicitProxy -ne $null) { - # explicit proxy - $proxy = New-Object System.Net.WebProxy($explicitProxy, $true) - if ($explicitProxyPassword -ne $null) { - $passwd = ConvertTo-SecureString $explicitProxyPassword -AsPlainText -Force - $proxy.Credentials = New-Object System.Management.Automation.PSCredential ($explicitProxyUser, $passwd) - } - - if ($explicitProxyBypassList -ne $null -and $explicitProxyBypassList -ne '') { - $proxy.BypassList = $explicitProxyBypassList.Split(',', [System.StringSplitOptions]::RemoveEmptyEntries) + catch { + #continue on } - if ($explicitProxyBypassOnLocal -eq 'true') { $proxy.BypassProxyOnLocal = $true; } - - Write-Host "Using explicit proxy server '$explicitProxy'." - $req.Proxy = $proxy - } elseif ($webclient.Proxy -and !$webclient.Proxy.IsBypassed($url)) { - # system proxy (pass through) - $creds = [net.CredentialCache]::DefaultCredentials - if ($creds -eq $null) { - Write-Debug "Default credentials were null. Attempting backup method" - $cred = get-credential - $creds = $cred.GetNetworkCredential(); + + $req = [System.Net.HttpWebRequest]::Create($url); + $defaultCreds = [System.Net.CredentialCache]::DefaultCredentials + if ($defaultCreds -ne $null) { + $req.Credentials = $defaultCreds } - $proxyaddress = $webclient.Proxy.GetProxy($url).Authority - Write-Host "Using system proxy server '$proxyaddress'." - $proxy = New-Object System.Net.WebProxy($proxyaddress) - $proxy.Credentials = $creds - $proxy.BypassProxyOnLocal = $true - $req.Proxy = $proxy - } - - $req.Accept = "*/*" - $req.AllowAutoRedirect = $true - $req.MaximumAutomaticRedirections = 20 - #$req.KeepAlive = $true - $req.AutomaticDecompression = [System.Net.DecompressionMethods]::GZip -bor [System.Net.DecompressionMethods]::Deflate - $req.Timeout = 30000 - if ($env:chocolateyRequestTimeout -ne $null -and $env:chocolateyRequestTimeout -ne '') { - Write-Debug "Setting request timeout to $env:chocolateyRequestTimeout" - $req.Timeout = $env:chocolateyRequestTimeout - } - if ($env:chocolateyResponseTimeout -ne $null -and $env:chocolateyResponseTimeout -ne '') { - Write-Debug "Setting read/write timeout to $env:chocolateyResponseTimeout" - $req.ReadWriteTimeout = $env:chocolateyResponseTimeout - } - - #http://stackoverflow.com/questions/518181/too-many-automatic-redirections-were-attempted-error-message-when-using-a-httpw - $req.CookieContainer = New-Object System.Net.CookieContainer - if ($userAgent -ne $null) { - Write-Debug "Setting the UserAgent to `'$userAgent`'" - $req.UserAgent = $userAgent - } - - if ($options.Headers.Count -gt 0) { - Write-Debug "Setting custom headers" - foreach ($key in $options.headers.keys) { - $uri = (New-Object -Typename system.uri $url) - switch ($key) { - 'Accept' {$req.Accept = $options.headers.$key} - 'Cookie' {$req.CookieContainer.SetCookies($uri, $options.headers.$key)} - 'Referer' {$req.Referer = $options.headers.$key} - 'User-Agent' {$req.UserAgent = $options.headers.$key} - Default {$req.Headers.Add($key, $options.headers.$key)} - } + + $webclient = New-Object System.Net.WebClient + if ($defaultCreds -ne $null) { + $webClient.Credentials = $defaultCreds } - } - try { - $res = $req.GetResponse(); + # check if a proxy is required + $explicitProxy = $env:chocolateyProxyLocation + $explicitProxyUser = $env:chocolateyProxyUser + $explicitProxyPassword = $env:chocolateyProxyPassword + $explicitProxyBypassList = $env:chocolateyProxyBypassList + $explicitProxyBypassOnLocal = $env:chocolateyProxyBypassOnLocal + if ($explicitProxy -ne $null) { + # explicit proxy + $proxy = New-Object System.Net.WebProxy($explicitProxy, $true) + if ($explicitProxyPassword -ne $null) { + $passwd = ConvertTo-SecureString $explicitProxyPassword -AsPlainText -Force + $proxy.Credentials = New-Object System.Management.Automation.PSCredential ($explicitProxyUser, $passwd) + } - try { - $headers = @{} - foreach ($key in $res.Headers) { - $value = $res.Headers[$key]; - if ($value) { - $headers.Add("$key","$value") + if ($explicitProxyBypassList -ne $null -and $explicitProxyBypassList -ne '') { + $proxy.BypassList = $explicitProxyBypassList.Split(',', [System.StringSplitOptions]::RemoveEmptyEntries) } - } - - $binaryIsTextCheckFile = "$fileName.istext" - if (Test-Path($binaryIsTextCheckFile)) { Remove-Item $binaryIsTextCheckFile -Force -EA SilentlyContinue; } - - if ($headers.ContainsKey("Content-Type")) { - $contentType = $headers['Content-Type'] - if ($null -ne $contentType) { - if ($contentType.ToLower().Contains("text/html") -or $contentType.ToLower().Contains("text/plain")) { - Write-Warning "$fileName is of content type $contentType" - Set-Content -Path $binaryIsTextCheckFile -Value "$fileName has content type $contentType" -Encoding UTF8 -Force - } + if ($explicitProxyBypassOnLocal -eq 'true') { + $proxy.BypassProxyOnLocal = $true; } - } - } catch { - # not able to get content-type header - Write-Debug "Error getting content type - $($_.Exception.Message)" + + Write-Host "Using explicit proxy server '$explicitProxy'." + $req.Proxy = $proxy + } + elseif ($webclient.Proxy -and !$webclient.Proxy.IsBypassed($url)) { + # system proxy (pass through) + $creds = [net.CredentialCache]::DefaultCredentials + if ($creds -eq $null) { + Write-Debug "Default credentials were null. Attempting backup method" + $cred = Get-Credential + $creds = $cred.GetNetworkCredential(); + } + $proxyaddress = $webclient.Proxy.GetProxy($url).Authority + Write-Host "Using system proxy server '$proxyaddress'." + $proxy = New-Object System.Net.WebProxy($proxyaddress) + $proxy.Credentials = $creds + $proxy.BypassProxyOnLocal = $true + $req.Proxy = $proxy } - if($fileName -and !(Split-Path $fileName)) { - $fileName = Join-Path (Get-Location -PSProvider "FileSystem") $fileName + $req.Accept = "*/*" + $req.AllowAutoRedirect = $true + $req.MaximumAutomaticRedirections = 20 + #$req.KeepAlive = $true + $req.AutomaticDecompression = [System.Net.DecompressionMethods]::GZip -bor [System.Net.DecompressionMethods]::Deflate + $req.Timeout = 30000 + if ($env:chocolateyRequestTimeout -ne $null -and $env:chocolateyRequestTimeout -ne '') { + Write-Debug "Setting request timeout to $env:chocolateyRequestTimeout" + $req.Timeout = $env:chocolateyRequestTimeout } - elseif((!$Passthru -and ($fileName -eq $null)) -or (($fileName -ne $null) -and (Test-Path -PathType "Container" $fileName))) - { - [string]$fileName = ([regex]'(?i)filename=(.*)$').Match( $res.Headers["Content-Disposition"] ).Groups[1].Value - $fileName = $fileName.trim("\/""'") - if(!$fileName) { - $fileName = $res.ResponseUri.Segments[-1] - $fileName = $fileName.trim("\/") - if(!$fileName) { - $fileName = Read-Host "Please provide a file name" - } - $fileName = $fileName.trim("\/") - if(!([IO.FileInfo]$fileName).Extension) { - $fileName = $fileName + "." + $res.ContentType.Split(";")[0].Split("/")[1] - } - } - $fileName = Join-Path (Get-Location -PSProvider "FileSystem") $fileName + if ($env:chocolateyResponseTimeout -ne $null -and $env:chocolateyResponseTimeout -ne '') { + Write-Debug "Setting read/write timeout to $env:chocolateyResponseTimeout" + $req.ReadWriteTimeout = $env:chocolateyResponseTimeout } - if($Passthru) { - $encoding = [System.Text.Encoding]::GetEncoding( $res.CharacterSet ) - [string]$output = "" + + #http://stackoverflow.com/questions/518181/too-many-automatic-redirections-were-attempted-error-message-when-using-a-httpw + $req.CookieContainer = New-Object System.Net.CookieContainer + if ($userAgent -ne $null) { + Write-Debug "Setting the UserAgent to `'$userAgent`'" + $req.UserAgent = $userAgent } - if($res.StatusCode -eq 401 -or $res.StatusCode -eq 403 -or $res.StatusCode -eq 404) { - $env:ChocolateyExitCode = $res.StatusCode - throw "Remote file either doesn't exist, is unauthorized, or is forbidden for '$url'." + if ($options.Headers.Count -gt 0) { + Write-Debug "Setting custom headers" + foreach ($key in $options.headers.keys) { + $uri = (New-Object -TypeName system.uri $url) + switch ($key) { + 'Accept' { + $req.Accept = $options.headers.$key + } + 'Cookie' { + $req.CookieContainer.SetCookies($uri, $options.headers.$key) + } + 'Referer' { + $req.Referer = $options.headers.$key + } + 'User-Agent' { + $req.UserAgent = $options.headers.$key + } + Default { + $req.Headers.Add($key, $options.headers.$key) + } + } + } } - if($res.StatusCode -eq 200) { - [long]$goal = $res.ContentLength - $goalFormatted = Format-FileSize $goal - $reader = $res.GetResponseStream() + try { + $res = $req.GetResponse(); + + try { + $headers = @{} + foreach ($key in $res.Headers) { + $value = $res.Headers[$key]; + if ($value) { + $headers.Add("$key", "$value") + } + } + + $binaryIsTextCheckFile = "$fileName.istext" + if (Test-Path($binaryIsTextCheckFile)) { + Remove-Item $binaryIsTextCheckFile -Force -EA SilentlyContinue; + } - if ($fileName) { - $fileDirectory = $([System.IO.Path]::GetDirectoryName($fileName)) - if (!(Test-Path($fileDirectory))) { - [System.IO.Directory]::CreateDirectory($fileDirectory) | Out-Null + if ($headers.ContainsKey("Content-Type")) { + $contentType = $headers['Content-Type'] + if ($null -ne $contentType) { + if ($contentType.ToLower().Contains("text/html") -or $contentType.ToLower().Contains("text/plain")) { + Write-Warning "$fileName is of content type $contentType" + Set-Content -Path $binaryIsTextCheckFile -Value "$fileName has content type $contentType" -Encoding UTF8 -Force + } + } + } + } + catch { + # not able to get content-type header + Write-Debug "Error getting content type - $($_.Exception.Message)" } - try { - $writer = new-object System.IO.FileStream $fileName, "Create" - } catch { - throw $_.Exception + if ($fileName -and !(Split-Path $fileName)) { + $fileName = Join-Path (Get-Location -PSProvider "FileSystem") $fileName } - } - - [byte[]]$buffer = new-object byte[] 1048576 - [long]$total = [long]$count = [long]$iterLoop =0 - - $originalEAP = $ErrorActionPreference - $ErrorActionPreference = 'Stop' - try { - do - { - $count = $reader.Read($buffer, 0, $buffer.Length); - if($fileName) { - $writer.Write($buffer, 0, $count); - } - - if($Passthru){ - $output += $encoding.GetString($buffer,0,$count) - } elseif(!$quiet) { - $total += $count - $totalFormatted = Format-FileSize $total - if($goal -gt 0 -and ++$iterLoop%10 -eq 0) { - $percentComplete = [Math]::Truncate(($total/$goal)*100) - Write-Progress "Downloading $url to $fileName" "Saving $totalFormatted of $goalFormatted" -id 0 -percentComplete $percentComplete + elseif ((!$Passthru -and ($fileName -eq $null)) -or (($fileName -ne $null) -and (Test-Path -PathType "Container" $fileName))) { + [string]$fileName = ([regex]'(?i)filename=(.*)$').Match( $res.Headers["Content-Disposition"] ).Groups[1].Value + $fileName = $fileName.trim("\/""'") + if (!$fileName) { + $fileName = $res.ResponseUri.Segments[-1] + $fileName = $fileName.trim("\/") + if (!$fileName) { + $fileName = Read-Host "Please provide a file name" + } + $fileName = $fileName.trim("\/") + if (!([IO.FileInfo]$fileName).Extension) { + $fileName = $fileName + "." + $res.ContentType.Split(";")[0].Split("/")[1] + } } + $fileName = Join-Path (Get-Location -PSProvider "FileSystem") $fileName + } + if ($Passthru) { + $encoding = [System.Text.Encoding]::GetEncoding( $res.CharacterSet ) + [string]$output = "" + } - if ($total -eq $goal -and $count -eq 0) { - Write-Progress "Completed download of $url." "Completed download of $fileName ($goalFormatted)." -id 0 -Completed -PercentComplete 100 + if ($res.StatusCode -eq 401 -or $res.StatusCode -eq 403 -or $res.StatusCode -eq 404) { + $env:ChocolateyExitCode = $res.StatusCode + throw "Remote file either doesn't exist, is unauthorized, or is forbidden for '$url'." + } + + if ($res.StatusCode -eq 200) { + [long]$goal = $res.ContentLength + $goalFormatted = Format-FileSize $goal + $reader = $res.GetResponseStream() + + if ($fileName) { + $fileDirectory = $([System.IO.Path]::GetDirectoryName($fileName)) + if (!(Test-Path($fileDirectory))) { + [System.IO.Directory]::CreateDirectory($fileDirectory) | Out-Null + } + + try { + $writer = New-Object System.IO.FileStream $fileName, "Create" + } + catch { + throw $_.Exception + } + } + + [byte[]]$buffer = New-Object byte[] 1048576 + [long]$total = [long]$count = [long]$iterLoop = 0 + + $originalEAP = $ErrorActionPreference + $ErrorActionPreference = 'Stop' + try { + do { + $count = $reader.Read($buffer, 0, $buffer.Length); + if ($fileName) { + $writer.Write($buffer, 0, $count); + } + + if ($Passthru) { + $output += $encoding.GetString($buffer, 0, $count) + } + elseif (!$quiet) { + $total += $count + $totalFormatted = Format-FileSize $total + if ($goal -gt 0 -and ++$iterLoop % 10 -eq 0) { + $percentComplete = [Math]::Truncate(($total / $goal) * 100) + Write-Progress "Downloading $url to $fileName" "Saving $totalFormatted of $goalFormatted" -Id 0 -PercentComplete $percentComplete + } + + if ($total -eq $goal -and $count -eq 0) { + Write-Progress "Completed download of $url." "Completed download of $fileName ($goalFormatted)." -Id 0 -Completed -PercentComplete 100 + } + } + } while ($count -gt 0) + Write-Host "" + Write-Host "Download of $([System.IO.Path]::GetFileName($fileName)) ($goalFormatted) completed." + } + catch { + throw $_.Exception + } + finally { + $ErrorActionPreference = $originalEAP } - } - } while ($count -gt 0) - Write-Host "" - Write-Host "Download of $([System.IO.Path]::GetFileName($fileName)) ($goalFormatted) completed." - } catch { - throw $_.Exception - } finally { - $ErrorActionPreference = $originalEAP - } - - $reader.Close() - if($fileName) { - $writer.Flush() - $writer.Close() - } - if($Passthru){ - $output - } - } - } catch { - if ($null -ne $req) { - $req.ServicePoint.MaxIdleTime = 0 - $req.Abort(); - # ruthlessly remove $req to ensure it isn't reused - Remove-Variable req - Start-Sleep 1 - [GC]::Collect() - } - Set-PowerShellExitCode 404 - if ($env:DownloadCacheAvailable -eq 'true') { - throw "The remote file either doesn't exist, is unauthorized, or is forbidden for url '$url'. $($_.Exception.Message) `nThis package is likely not broken for licensed users - see https://docs.chocolatey.org/en-us/features/private-cdn." - } else { - throw "The remote file either doesn't exist, is unauthorized, or is forbidden for url '$url'. $($_.Exception.Message)" + $reader.Close() + if ($fileName) { + $writer.Flush() + $writer.Close() + } + if ($Passthru) { + $output + } + } } - } finally { - if ($null -ne $res) { - $res.Close() + catch { + if ($null -ne $req) { + $req.ServicePoint.MaxIdleTime = 0 + $req.Abort(); + # ruthlessly remove $req to ensure it isn't reused + Remove-Variable req + Start-Sleep 1 + [GC]::Collect() + } + + Set-PowerShellExitCode 404 + if ($env:DownloadCacheAvailable -eq 'true') { + throw "The remote file either doesn't exist, is unauthorized, or is forbidden for url '$url'. $($_.Exception.Message) `nThis package is likely not broken for licensed users - see https://docs.chocolatey.org/en-us/features/private-cdn." + } + else { + throw "The remote file either doesn't exist, is unauthorized, or is forbidden for url '$url'. $($_.Exception.Message)" + } } + finally { + if ($null -ne $res) { + $res.Close() + } - Start-Sleep 1 - } + Start-Sleep 1 + } } # this could be cleaned up with http://learn-powershell.net/2013/02/08/powershell-and-events-object-events/ diff --git a/src/chocolatey.resources/helpers/functions/Get-WebFileName.ps1 b/src/chocolatey.resources/helpers/functions/Get-WebFileName.ps1 index f9fa317f56..b2c3de28db 100644 --- a/src/chocolatey.resources/helpers/functions/Get-WebFileName.ps1 +++ b/src/chocolatey.resources/helpers/functions/Get-WebFileName.ps1 @@ -16,7 +16,7 @@ # Based on http://stackoverflow.com/a/13571471/18475 function Get-WebFileName { -<# + <# .SYNOPSIS Gets the original file name from a url. Used by Get-WebFile to determine the original file name for a file. @@ -66,190 +66,200 @@ Get-WebHeaders .LINK Get-ChocolateyWebFile #> -param( - [parameter(Mandatory=$false, Position=0)][string] $url = '', - [parameter(Mandatory=$true, Position=1)][string] $defaultName, - [parameter(Mandatory=$false)][string] $userAgent = 'chocolatey command line', - [parameter(ValueFromRemainingArguments = $true)][Object[]] $ignoredArguments -) - - Write-FunctionCallLogMessage -Invocation $MyInvocation -Parameters $PSBoundParameters - - $originalFileName = $defaultName - $fileName = $null - - if ($url -eq $null -or $url -eq '') { - Write-Debug "Url was null, using default name." - return $originalFileName - } - - try { - $uri = [System.Uri]$url - if ($uri.IsFile()) { - $fileName = [System.IO.Path]::GetFileName($uri.LocalPath) - Write-Debug "Url is local file, returning fileName" - - return $fileName - } - } catch { - #continue on - } - - if ($url.StartsWith('ftp')) { - Write-Debug "Url is FTP, using default name." - return $originalFileName - } - - $request = [System.Net.HttpWebRequest]::Create($url) - if ($request -eq $null) { - Write-Debug "Request was null, using default name." - return $originalFileName - } - - $defaultCreds = [System.Net.CredentialCache]::DefaultCredentials - if ($defaultCreds -ne $null) { - $request.Credentials = $defaultCreds - } - - $client = New-Object System.Net.WebClient - if ($defaultCreds -ne $null) { - $client.Credentials = $defaultCreds - } - - # check if a proxy is required - $explicitProxy = $env:chocolateyProxyLocation - $explicitProxyUser = $env:chocolateyProxyUser - $explicitProxyPassword = $env:chocolateyProxyPassword - $explicitProxyBypassList = $env:chocolateyProxyBypassList - $explicitProxyBypassOnLocal = $env:chocolateyProxyBypassOnLocal - if ($explicitProxy -ne $null) { - # explicit proxy - $proxy = New-Object System.Net.WebProxy($explicitProxy, $true) - if ($explicitProxyPassword -ne $null) { - $passwd = ConvertTo-SecureString $explicitProxyPassword -AsPlainText -Force - $proxy.Credentials = New-Object System.Management.Automation.PSCredential ($explicitProxyUser, $passwd) - } + param( + [parameter(Mandatory = $false, Position = 0)][string] $url = '', + [parameter(Mandatory = $true, Position = 1)][string] $defaultName, + [parameter(Mandatory = $false)][string] $userAgent = 'chocolatey command line', + [parameter(ValueFromRemainingArguments = $true)][Object[]] $ignoredArguments + ) + + Write-FunctionCallLogMessage -Invocation $MyInvocation -Parameters $PSBoundParameters + + $originalFileName = $defaultName + $fileName = $null - if ($explicitProxyBypassList -ne $null -and $explicitProxyBypassList -ne '') { - $proxy.BypassList = $explicitProxyBypassList.Split(',', [System.StringSplitOptions]::RemoveEmptyEntries) + if ($url -eq $null -or $url -eq '') { + Write-Debug "Url was null, using default name." + return $originalFileName } - if ($explicitProxyBypassOnLocal -eq 'true') { $proxy.BypassProxyOnLocal = $true; } - - Write-Debug "Using explicit proxy server '$explicitProxy'." - $request.Proxy = $proxy - - } elseif ($client.Proxy -and !$client.Proxy.IsBypassed($url)) { - # system proxy (pass through) - $creds = [Net.CredentialCache]::DefaultCredentials - if ($creds -eq $null) { - Write-Debug "Default credentials were null. Attempting backup method" - $cred = Get-Credential - $creds = $cred.GetNetworkCredential(); + + try { + $uri = [System.Uri]$url + if ($uri.IsFile()) { + $fileName = [System.IO.Path]::GetFileName($uri.LocalPath) + Write-Debug "Url is local file, returning fileName" + + return $fileName + } } - $proxyAddress = $client.Proxy.GetProxy($url).Authority - Write-Debug "Using system proxy server '$proxyaddress'." - $proxy = New-Object System.Net.WebProxy($proxyAddress) - $proxy.Credentials = $creds - $proxy.BypassProxyOnLocal = $true - $request.Proxy = $proxy - } - - $request.Method = "GET" - $request.Accept = '*/*' - $request.AllowAutoRedirect = $true - $request.MaximumAutomaticRedirections = 20 - #$request.KeepAlive = $true - $request.AutomaticDecompression = [System.Net.DecompressionMethods]::GZip -bor [System.Net.DecompressionMethods]::Deflate - $request.Timeout = 30000 - if ($env:chocolateyRequestTimeout -ne $null -and $env:chocolateyRequestTimeout -ne '') { - $request.Timeout = $env:chocolateyRequestTimeout - } - if ($env:chocolateyResponseTimeout -ne $null -and $env:chocolateyResponseTimeout -ne '') { - $request.ReadWriteTimeout = $env:chocolateyResponseTimeout - } - - #http://stackoverflow.com/questions/518181/too-many-automatic-redirections-were-attempted-error-message-when-using-a-httpw - $request.CookieContainer = New-Object System.Net.CookieContainer - $request.UserAgent = $userAgent - - [System.Text.RegularExpressions.Regex]$containsABadCharacter = New-Object Regex("[" + [System.Text.RegularExpressions.Regex]::Escape([System.IO.Path]::GetInvalidFileNameChars() -join '') + "\=\;]"); - - try - { - [System.Net.HttpWebResponse]$response = $request.GetResponse() - if ($response -eq $null) { - Write-Debug "Response was null, using default name." - return $originalFileName + catch { + #continue on } - [string]$header = $response.Headers['Content-Disposition'] - [string]$headerLocation = $response.Headers['Location'] - - # start with content-disposition header - if ($header -ne '') { - $fileHeaderName = 'filename=' - $index = $header.LastIndexOf($fileHeaderName, [StringComparison]::OrdinalIgnoreCase) - if ($index -gt -1) { - Write-Debug "Using header 'Content-Disposition' to determine file name." - $fileName = $header.Substring($index + $fileHeaderName.Length).Replace('"', '') - } - } - if ($containsABadCharacter.IsMatch($fileName)) { $fileName = $null } - - # If empty, check location header next - if ($fileName -eq $null -or $fileName -eq '') { - if ($headerLocation -ne '') { - Write-Debug "Using header 'Location' to determine file name." - $fileName = [System.IO.Path]::GetFileName($headerLocation) - } + if ($url.StartsWith('ftp')) { + Write-Debug "Url is FTP, using default name." + return $originalFileName } - if ($containsABadCharacter.IsMatch($fileName)) { $fileName = $null } - - # Next comes using the response url value - if ($fileName -eq $null -or $fileName -eq '') { - $responseUrl = $response.ResponseUri.ToString() - if (!$responseUrl.Contains('?')) { - Write-Debug "Using response url to determine file name. '$responseUrl'" - $fileName = [System.IO.Path]::GetFileName($responseUrl) - } + + $request = [System.Net.HttpWebRequest]::Create($url) + if ($request -eq $null) { + Write-Debug "Request was null, using default name." + return $originalFileName } - if ($containsABadCharacter.IsMatch($fileName)) { $fileName = $null } - - # Next comes using the request url value - if ($fileName -eq $null -or $fileName -eq '') { - $requestUrl = $url - $extension = [System.IO.Path]::GetExtension($requestUrl) - if (!$requestUrl.Contains('?') -and $extension -ne $null -and $extension -ne '') { - Write-Debug "Using request url to determine file name. ' $requestUrl'" - $fileName = [System.IO.Path]::GetFileName($requestUrl) - } + + $defaultCreds = [System.Net.CredentialCache]::DefaultCredentials + if ($defaultCreds -ne $null) { + $request.Credentials = $defaultCreds } - # when all else fails, default the name - if ($fileName -eq $null -or $fileName -eq '' -or $containsABadCharacter.IsMatch($fileName)) { - Write-Debug "File name is null or illegal. Using $originalFileName instead." - $fileName = $originalFileName + $client = New-Object System.Net.WebClient + if ($defaultCreds -ne $null) { + $client.Credentials = $defaultCreds } - Write-Debug "File name determined from url is '$fileName'" - - return $fileName - } catch { - if ($request -ne $null) { - $request.ServicePoint.MaxIdleTime = 0 - $request.Abort(); - # ruthlessly remove $request to ensure it isn't reused - Remove-Variable request - Start-Sleep 1 - [GC]::Collect() + # check if a proxy is required + $explicitProxy = $env:chocolateyProxyLocation + $explicitProxyUser = $env:chocolateyProxyUser + $explicitProxyPassword = $env:chocolateyProxyPassword + $explicitProxyBypassList = $env:chocolateyProxyBypassList + $explicitProxyBypassOnLocal = $env:chocolateyProxyBypassOnLocal + if ($explicitProxy -ne $null) { + # explicit proxy + $proxy = New-Object System.Net.WebProxy($explicitProxy, $true) + if ($explicitProxyPassword -ne $null) { + $passwd = ConvertTo-SecureString $explicitProxyPassword -AsPlainText -Force + $proxy.Credentials = New-Object System.Management.Automation.PSCredential ($explicitProxyUser, $passwd) + } + + if ($explicitProxyBypassList -ne $null -and $explicitProxyBypassList -ne '') { + $proxy.BypassList = $explicitProxyBypassList.Split(',', [System.StringSplitOptions]::RemoveEmptyEntries) + } + if ($explicitProxyBypassOnLocal -eq 'true') { + $proxy.BypassProxyOnLocal = $true; + } + + Write-Debug "Using explicit proxy server '$explicitProxy'." + $request.Proxy = $proxy + } + elseif ($client.Proxy -and !$client.Proxy.IsBypassed($url)) { + # system proxy (pass through) + $creds = [Net.CredentialCache]::DefaultCredentials + if ($creds -eq $null) { + Write-Debug "Default credentials were null. Attempting backup method" + $cred = Get-Credential + $creds = $cred.GetNetworkCredential(); + } + $proxyAddress = $client.Proxy.GetProxy($url).Authority + Write-Debug "Using system proxy server '$proxyaddress'." + $proxy = New-Object System.Net.WebProxy($proxyAddress) + $proxy.Credentials = $creds + $proxy.BypassProxyOnLocal = $true + $request.Proxy = $proxy } - Write-Debug "Url request/response failed - file name will be '$originalFileName': $($_)" + $request.Method = "GET" + $request.Accept = '*/*' + $request.AllowAutoRedirect = $true + $request.MaximumAutomaticRedirections = 20 + #$request.KeepAlive = $true + $request.AutomaticDecompression = [System.Net.DecompressionMethods]::GZip -bor [System.Net.DecompressionMethods]::Deflate + $request.Timeout = 30000 + if ($env:chocolateyRequestTimeout -ne $null -and $env:chocolateyRequestTimeout -ne '') { + $request.Timeout = $env:chocolateyRequestTimeout + } + if ($env:chocolateyResponseTimeout -ne $null -and $env:chocolateyResponseTimeout -ne '') { + $request.ReadWriteTimeout = $env:chocolateyResponseTimeout + } - return $originalFileName - } finally { - if ($response -ne $null) { - $response.Close(); + #http://stackoverflow.com/questions/518181/too-many-automatic-redirections-were-attempted-error-message-when-using-a-httpw + $request.CookieContainer = New-Object System.Net.CookieContainer + $request.UserAgent = $userAgent + + [System.Text.RegularExpressions.Regex]$containsABadCharacter = New-Object Regex("[" + [System.Text.RegularExpressions.Regex]::Escape([System.IO.Path]::GetInvalidFileNameChars() -join '') + "\=\;]"); + + try { + [System.Net.HttpWebResponse]$response = $request.GetResponse() + if ($response -eq $null) { + Write-Debug "Response was null, using default name." + return $originalFileName + } + + [string]$header = $response.Headers['Content-Disposition'] + [string]$headerLocation = $response.Headers['Location'] + + # start with content-disposition header + if ($header -ne '') { + $fileHeaderName = 'filename=' + $index = $header.LastIndexOf($fileHeaderName, [StringComparison]::OrdinalIgnoreCase) + if ($index -gt -1) { + Write-Debug "Using header 'Content-Disposition' to determine file name." + $fileName = $header.Substring($index + $fileHeaderName.Length).Replace('"', '') + } + } + if ($containsABadCharacter.IsMatch($fileName)) { + $fileName = $null + } + + # If empty, check location header next + if ($fileName -eq $null -or $fileName -eq '') { + if ($headerLocation -ne '') { + Write-Debug "Using header 'Location' to determine file name." + $fileName = [System.IO.Path]::GetFileName($headerLocation) + } + } + if ($containsABadCharacter.IsMatch($fileName)) { + $fileName = $null + } + + # Next comes using the response url value + if ($fileName -eq $null -or $fileName -eq '') { + $responseUrl = $response.ResponseUri.ToString() + if (!$responseUrl.Contains('?')) { + Write-Debug "Using response url to determine file name. '$responseUrl'" + $fileName = [System.IO.Path]::GetFileName($responseUrl) + } + } + if ($containsABadCharacter.IsMatch($fileName)) { + $fileName = $null + } + + # Next comes using the request url value + if ($fileName -eq $null -or $fileName -eq '') { + $requestUrl = $url + $extension = [System.IO.Path]::GetExtension($requestUrl) + if (!$requestUrl.Contains('?') -and $extension -ne $null -and $extension -ne '') { + Write-Debug "Using request url to determine file name. ' $requestUrl'" + $fileName = [System.IO.Path]::GetFileName($requestUrl) + } + } + + # when all else fails, default the name + if ($fileName -eq $null -or $fileName -eq '' -or $containsABadCharacter.IsMatch($fileName)) { + Write-Debug "File name is null or illegal. Using $originalFileName instead." + $fileName = $originalFileName + } + + Write-Debug "File name determined from url is '$fileName'" + + return $fileName + } + catch { + if ($request -ne $null) { + $request.ServicePoint.MaxIdleTime = 0 + $request.Abort(); + # ruthlessly remove $request to ensure it isn't reused + Remove-Variable request + Start-Sleep 1 + [GC]::Collect() + } + + Write-Debug "Url request/response failed - file name will be '$originalFileName': $($_)" + + return $originalFileName + } + finally { + if ($response -ne $null) { + $response.Close(); + } } - } } diff --git a/src/chocolatey.resources/helpers/functions/Get-WebHeaders.ps1 b/src/chocolatey.resources/helpers/functions/Get-WebHeaders.ps1 index 12c0d9c97b..02cb01d730 100644 --- a/src/chocolatey.resources/helpers/functions/Get-WebHeaders.ps1 +++ b/src/chocolatey.resources/helpers/functions/Get-WebHeaders.ps1 @@ -15,7 +15,7 @@ # limitations under the License. function Get-WebHeaders { -<# + <# .SYNOPSIS Gets the request/response headers for a url. @@ -49,123 +49,130 @@ Get-WebFileName .LINK Get-WebFile #> -param( - [parameter(Mandatory=$false, Position=0)][string] $url = '', - [parameter(Mandatory=$false, Position=1)][string] $userAgent = 'chocolatey command line', - [parameter(ValueFromRemainingArguments = $true)][Object[]] $ignoredArguments -) - - Write-FunctionCallLogMessage -Invocation $MyInvocation -Parameters $PSBoundParameters - - if ($url -eq '') { return @{} } - - $request = [System.Net.HttpWebRequest]::Create($url); - $defaultCreds = [System.Net.CredentialCache]::DefaultCredentials - if ($defaultCreds -ne $null) { - $request.Credentials = $defaultCreds - } - - #$request.Method = "HEAD" - $client = New-Object System.Net.WebClient - if ($defaultCreds -ne $null) { - $client.Credentials = $defaultCreds - } - - # check if a proxy is required - $explicitProxy = $env:chocolateyProxyLocation - $explicitProxyUser = $env:chocolateyProxyUser - $explicitProxyPassword = $env:chocolateyProxyPassword - $explicitProxyBypassList = $env:chocolateyProxyBypassList - $explicitProxyBypassOnLocal = $env:chocolateyProxyBypassOnLocal - if ($explicitProxy -ne $null) { - # explicit proxy - $proxy = New-Object System.Net.WebProxy($explicitProxy, $true) - if ($explicitProxyPassword -ne $null) { - $passwd = ConvertTo-SecureString $explicitProxyPassword -AsPlainText -Force - $proxy.Credentials = New-Object System.Management.Automation.PSCredential ($explicitProxyUser, $passwd) + param( + [parameter(Mandatory = $false, Position = 0)][string] $url = '', + [parameter(Mandatory = $false, Position = 1)][string] $userAgent = 'chocolatey command line', + [parameter(ValueFromRemainingArguments = $true)][Object[]] $ignoredArguments + ) + + Write-FunctionCallLogMessage -Invocation $MyInvocation -Parameters $PSBoundParameters + + if ($url -eq '') { + return @{} + } + + $request = [System.Net.HttpWebRequest]::Create($url); + $defaultCreds = [System.Net.CredentialCache]::DefaultCredentials + if ($defaultCreds -ne $null) { + $request.Credentials = $defaultCreds + } + + #$request.Method = "HEAD" + $client = New-Object System.Net.WebClient + if ($defaultCreds -ne $null) { + $client.Credentials = $defaultCreds } - if ($explicitProxyBypassList -ne $null -and $explicitProxyBypassList -ne '') { - $proxy.BypassList = $explicitProxyBypassList.Split(',', [System.StringSplitOptions]::RemoveEmptyEntries) + # check if a proxy is required + $explicitProxy = $env:chocolateyProxyLocation + $explicitProxyUser = $env:chocolateyProxyUser + $explicitProxyPassword = $env:chocolateyProxyPassword + $explicitProxyBypassList = $env:chocolateyProxyBypassList + $explicitProxyBypassOnLocal = $env:chocolateyProxyBypassOnLocal + if ($explicitProxy -ne $null) { + # explicit proxy + $proxy = New-Object System.Net.WebProxy($explicitProxy, $true) + if ($explicitProxyPassword -ne $null) { + $passwd = ConvertTo-SecureString $explicitProxyPassword -AsPlainText -Force + $proxy.Credentials = New-Object System.Management.Automation.PSCredential ($explicitProxyUser, $passwd) + } + + if ($explicitProxyBypassList -ne $null -and $explicitProxyBypassList -ne '') { + $proxy.BypassList = $explicitProxyBypassList.Split(',', [System.StringSplitOptions]::RemoveEmptyEntries) + } + if ($explicitProxyBypassOnLocal -eq 'true') { + $proxy.BypassProxyOnLocal = $true; + } + + Write-Host "Using explicit proxy server '$explicitProxy'." + $request.Proxy = $proxy } - if ($explicitProxyBypassOnLocal -eq 'true') { $proxy.BypassProxyOnLocal = $true; } - - Write-Host "Using explicit proxy server '$explicitProxy'." - $request.Proxy = $proxy - - } elseif ($client.Proxy -and !$client.Proxy.IsBypassed($url)) { - # system proxy (pass through) - $creds = [Net.CredentialCache]::DefaultCredentials - if ($creds -eq $null) { - Write-Debug "Default credentials were null. Attempting backup method" - $cred = Get-Credential - $creds = $cred.GetNetworkCredential(); + elseif ($client.Proxy -and !$client.Proxy.IsBypassed($url)) { + # system proxy (pass through) + $creds = [Net.CredentialCache]::DefaultCredentials + if ($creds -eq $null) { + Write-Debug "Default credentials were null. Attempting backup method" + $cred = Get-Credential + $creds = $cred.GetNetworkCredential(); + } + $proxyAddress = $client.Proxy.GetProxy($url).Authority + Write-Host "Using system proxy server '$proxyaddress'." + $proxy = New-Object System.Net.WebProxy($proxyAddress) + $proxy.Credentials = $creds + $proxy.BypassProxyOnLocal = $true + $request.Proxy = $proxy } - $proxyAddress = $client.Proxy.GetProxy($url).Authority - Write-Host "Using system proxy server '$proxyaddress'." - $proxy = New-Object System.Net.WebProxy($proxyAddress) - $proxy.Credentials = $creds - $proxy.BypassProxyOnLocal = $true - $request.Proxy = $proxy - } - - $request.Accept = '*/*' - $request.AllowAutoRedirect = $true - $request.MaximumAutomaticRedirections = 20 - #$request.KeepAlive = $true - $request.AutomaticDecompression = [System.Net.DecompressionMethods]::GZip -bor [System.Net.DecompressionMethods]::Deflate - $request.Timeout = 30000 - if ($env:chocolateyRequestTimeout -ne $null -and $env:chocolateyRequestTimeout -ne '') { - $request.Timeout = $env:chocolateyRequestTimeout - } - if ($env:chocolateyResponseTimeout -ne $null -and $env:chocolateyResponseTimeout -ne '') { - $request.ReadWriteTimeout = $env:chocolateyResponseTimeout - } - - #http://stackoverflow.com/questions/518181/too-many-automatic-redirections-were-attempted-error-message-when-using-a-httpw - $request.CookieContainer = New-Object System.Net.CookieContainer - if ($userAgent -ne $null) { - Write-Debug "Setting the UserAgent to `'$userAgent`'" - $request.UserAgent = $userAgent - } - - Write-Debug "Request Headers:" - foreach ($key in $request.Headers) { - $value = $request.Headers[$key]; - if ($value) { - Write-Debug " `'$key`':`'$value`'" - } else { - Write-Debug " `'$key`'" + + $request.Accept = '*/*' + $request.AllowAutoRedirect = $true + $request.MaximumAutomaticRedirections = 20 + #$request.KeepAlive = $true + $request.AutomaticDecompression = [System.Net.DecompressionMethods]::GZip -bor [System.Net.DecompressionMethods]::Deflate + $request.Timeout = 30000 + if ($env:chocolateyRequestTimeout -ne $null -and $env:chocolateyRequestTimeout -ne '') { + $request.Timeout = $env:chocolateyRequestTimeout + } + if ($env:chocolateyResponseTimeout -ne $null -and $env:chocolateyResponseTimeout -ne '') { + $request.ReadWriteTimeout = $env:chocolateyResponseTimeout } - } - - $headers = @{} - try { - $response = $request.GetResponse(); - Write-Debug "Response Headers:" - foreach ($key in $response.Headers) { - $value = $response.Headers[$key]; - if ($value) { - $headers.Add("$key","$value") - Write-Debug " `'$key`':`'$value`'" - } + + #http://stackoverflow.com/questions/518181/too-many-automatic-redirections-were-attempted-error-message-when-using-a-httpw + $request.CookieContainer = New-Object System.Net.CookieContainer + if ($userAgent -ne $null) { + Write-Debug "Setting the UserAgent to `'$userAgent`'" + $request.UserAgent = $userAgent } - } catch { - if ($request -ne $null) { - $request.ServicePoint.MaxIdleTime = 0 - $request.Abort(); - # ruthlessly remove $request to ensure it isn't reused - Remove-Variable request - Start-Sleep 1 - [GC]::Collect() + + Write-Debug "Request Headers:" + foreach ($key in $request.Headers) { + $value = $request.Headers[$key]; + if ($value) { + Write-Debug " `'$key`':`'$value`'" + } + else { + Write-Debug " `'$key`'" + } } - throw "The remote file either doesn't exist, is unauthorized, or is forbidden for url '$url'. $($_.Exception.Message)" - } finally { - if ($response -ne $null) { - $response.Close(); + $headers = @{} + try { + $response = $request.GetResponse(); + Write-Debug "Response Headers:" + foreach ($key in $response.Headers) { + $value = $response.Headers[$key]; + if ($value) { + $headers.Add("$key", "$value") + Write-Debug " `'$key`':`'$value`'" + } + } + } + catch { + if ($request -ne $null) { + $request.ServicePoint.MaxIdleTime = 0 + $request.Abort(); + # ruthlessly remove $request to ensure it isn't reused + Remove-Variable request + Start-Sleep 1 + [GC]::Collect() + } + + throw "The remote file either doesn't exist, is unauthorized, or is forbidden for url '$url'. $($_.Exception.Message)" + } + finally { + if ($response -ne $null) { + $response.Close(); + } } - } - $headers + $headers } diff --git a/src/chocolatey.resources/helpers/functions/Install-BinFile.ps1 b/src/chocolatey.resources/helpers/functions/Install-BinFile.ps1 index 6897ba83a3..fbe90a4bd5 100644 --- a/src/chocolatey.resources/helpers/functions/Install-BinFile.ps1 +++ b/src/chocolatey.resources/helpers/functions/Install-BinFile.ps1 @@ -15,7 +15,7 @@ # limitations under the License. function Install-BinFile { -<# + <# .SYNOPSIS Creates a shim (or batch redirect) for a file that is on the PATH. @@ -75,98 +75,103 @@ Install-ChocolateyShortcut .LINK Install-ChocolateyPath #> -param( - [parameter(Mandatory=$true, Position=0)][string] $name, - [parameter(Mandatory=$true, Position=1)][string] $path, - [parameter(Mandatory=$false)] - [alias("isGui")][switch] $useStart, - [parameter(Mandatory=$false)][string] $command = '', - [parameter(ValueFromRemainingArguments = $true)][Object[]] $ignoredArguments -) - - Write-FunctionCallLogMessage -Invocation $MyInvocation -Parameters $PSBoundParameters - - $nugetPath = [System.IO.Path]::GetFullPath((Join-Path "$helpersPath" '..\')) - $nugetExePath = Join-Path "$nugetPath" 'bin' - $packageBatchFileName = Join-Path $nugetExePath "$name.bat" - $packageBashFileName = Join-Path $nugetExePath "$name" - $packageShimFileName = Join-Path $nugetExePath "$name.exe" - - if (Test-Path ($packageBatchFileName)) {Remove-Item $packageBatchFileName -force} - if (Test-Path ($packageBashFileName)) {Remove-Item $packageBashFileName -force} - $originalPath = $path - $path = $path.ToLower().Replace($nugetPath.ToLower(), "..\").Replace("\\","\") - - $ShimGenArgs = "-o `"$packageShimFileName`" -p `"$path`" -i `"$originalPath`"" - if ($command -ne $null -and $command -ne '') { - $ShimGenArgs +=" -c $command" - } - - if ($useStart) { - $ShimGenArgs +=" -gui" - } - - if ($debug) { - $ShimGenArgs +=" -debug" - } - - $ShimGen = Join-Path "$helpersPath" '..\tools\shimgen.exe' - if (!([System.IO.File]::Exists($ShimGen))) { - Update-SessionEnvironment - $ShimGen = Join-Path "$env:ChocolateyInstall" 'tools\shimgen.exe' - } - - $ShimGen = [System.IO.Path]::GetFullPath($ShimGen) - Write-Debug "ShimGen found at `'$ShimGen`'" - - Write-Debug "Calling $ShimGen $ShimGenArgs" - - if (Test-Path ("$ShimGen")) { - #Start-Process "$ShimGen" -ArgumentList "$ShimGenArgs" -Wait -WindowStyle Hidden - $process = New-Object System.Diagnostics.Process - $process.StartInfo = new-object System.Diagnostics.ProcessStartInfo($ShimGen, $ShimGenArgs) - $process.StartInfo.RedirectStandardOutput = $true - $process.StartInfo.RedirectStandardError = $true - $process.StartInfo.UseShellExecute = $false - $process.StartInfo.WindowStyle = [System.Diagnostics.ProcessWindowStyle]::Hidden - - $process.Start() | Out-Null - $process.WaitForExit() - } - - if (Test-Path ($packageShimFileName)) { - Write-Host "Added $packageShimFileName shim pointed to `'$path`'." - } else { - Write-Warning "An error occurred generating shim, using old method." - - $path = "%DIR%$($path)" - $pathBash = $path.Replace("%DIR%..\","`$DIR/../").Replace("\","/") - Write-Host "Adding $packageBatchFileName and pointing to `'$path`'." - Write-Host "Adding $packageBashFileName and pointing to `'$path`'." + param( + [parameter(Mandatory = $true, Position = 0)][string] $name, + [parameter(Mandatory = $true, Position = 1)][string] $path, + [parameter(Mandatory = $false)] + [alias("isGui")][switch] $useStart, + [parameter(Mandatory = $false)][string] $command = '', + [parameter(ValueFromRemainingArguments = $true)][Object[]] $ignoredArguments + ) + + Write-FunctionCallLogMessage -Invocation $MyInvocation -Parameters $PSBoundParameters + + $nugetPath = [System.IO.Path]::GetFullPath((Join-Path "$helpersPath" '..\')) + $nugetExePath = Join-Path "$nugetPath" 'bin' + $packageBatchFileName = Join-Path $nugetExePath "$name.bat" + $packageBashFileName = Join-Path $nugetExePath "$name" + $packageShimFileName = Join-Path $nugetExePath "$name.exe" + + if (Test-Path ($packageBatchFileName)) { + Remove-Item $packageBatchFileName -Force + } + if (Test-Path ($packageBashFileName)) { + Remove-Item $packageBashFileName -Force + } + $originalPath = $path + $path = $path.ToLower().Replace($nugetPath.ToLower(), "..\").Replace("\\", "\") + + $ShimGenArgs = "-o `"$packageShimFileName`" -p `"$path`" -i `"$originalPath`"" + if ($command -ne $null -and $command -ne '') { + $ShimGenArgs += " -c $command" + } + if ($useStart) { - Write-Host "Setting up $name as a non-command line application." -"@echo off + $ShimGenArgs += " -gui" + } + + if ($debug) { + $ShimGenArgs += " -debug" + } + + $ShimGen = Join-Path "$helpersPath" '..\tools\shimgen.exe' + if (!([System.IO.File]::Exists($ShimGen))) { + Update-SessionEnvironment + $ShimGen = Join-Path "$env:ChocolateyInstall" 'tools\shimgen.exe' + } + + $ShimGen = [System.IO.Path]::GetFullPath($ShimGen) + Write-Debug "ShimGen found at `'$ShimGen`'" + + Write-Debug "Calling $ShimGen $ShimGenArgs" + + if (Test-Path ("$ShimGen")) { + #Start-Process "$ShimGen" -ArgumentList "$ShimGenArgs" -Wait -WindowStyle Hidden + $process = New-Object System.Diagnostics.Process + $process.StartInfo = New-Object System.Diagnostics.ProcessStartInfo($ShimGen, $ShimGenArgs) + $process.StartInfo.RedirectStandardOutput = $true + $process.StartInfo.RedirectStandardError = $true + $process.StartInfo.UseShellExecute = $false + $process.StartInfo.WindowStyle = [System.Diagnostics.ProcessWindowStyle]::Hidden + + $process.Start() | Out-Null + $process.WaitForExit() + } + + if (Test-Path ($packageShimFileName)) { + Write-Host "Added $packageShimFileName shim pointed to `'$path`'." + } + else { + Write-Warning "An error occurred generating shim, using old method." + + $path = "%DIR%$($path)" + $pathBash = $path.Replace("%DIR%..\", "`$DIR/../").Replace("\", "/") + Write-Host "Adding $packageBatchFileName and pointing to `'$path`'." + Write-Host "Adding $packageBashFileName and pointing to `'$path`'." + if ($useStart) { + Write-Host "Setting up $name as a non-command line application." + "@echo off SET DIR=%~dp0% -start """" ""$path"" %*" | Out-File $packageBatchFileName -encoding ASCII +start """" ""$path"" %*" | Out-File $packageBatchFileName -Encoding ASCII - $sw = New-Object IO.StreamWriter "$packageBashFileName" - $sw.Write("#!/bin/sh`nDIR=`${0%/*}`n""$pathBash"" ""`$@"" &`n") - $sw.Close() - $sw.Dispose() - } else { + $sw = New-Object IO.StreamWriter "$packageBashFileName" + $sw.Write("#!/bin/sh`nDIR=`${0%/*}`n""$pathBash"" ""`$@"" &`n") + $sw.Close() + $sw.Dispose() + } + else { -"@echo off + "@echo off SET DIR=%~dp0% cmd /c """"$path"" %*"" -exit /b %ERRORLEVEL%" | Out-File $packageBatchFileName -encoding ASCII - - $sw = New-Object IO.StreamWriter "$packageBashFileName" - $sw.Write("#!/bin/sh`nDIR=`${0%/*}`n""$pathBash"" ""`$@""`nexit `$?`n") - $sw.Close() - $sw.Dispose() +exit /b %ERRORLEVEL%" | Out-File $packageBatchFileName -Encoding ASCII + $sw = New-Object IO.StreamWriter "$packageBashFileName" + $sw.Write("#!/bin/sh`nDIR=`${0%/*}`n""$pathBash"" ""`$@""`nexit `$?`n") + $sw.Close() + $sw.Dispose() + } } - } } Set-Alias Generate-BinFile Install-BinFile diff --git a/src/chocolatey.resources/helpers/functions/Install-ChocolateyEnvironmentVariable.ps1 b/src/chocolatey.resources/helpers/functions/Install-ChocolateyEnvironmentVariable.ps1 index f571b7de68..5520143fac 100644 --- a/src/chocolatey.resources/helpers/functions/Install-ChocolateyEnvironmentVariable.ps1 +++ b/src/chocolatey.resources/helpers/functions/Install-ChocolateyEnvironmentVariable.ps1 @@ -15,7 +15,7 @@ # limitations under the License. function Install-ChocolateyEnvironmentVariable { -<# + <# .SYNOPSIS **NOTE:** Administrative Access Required when `-VariableType 'Machine'.` @@ -87,36 +87,40 @@ Set-EnvironmentVariable .LINK Install-ChocolateyPath #> -param( - [parameter(Mandatory=$false, Position=0)][string] $variableName, - [parameter(Mandatory=$false, Position=1)][string] $variableValue, - [parameter(Mandatory=$false, Position=2)] - [System.EnvironmentVariableTarget] $variableType = [System.EnvironmentVariableTarget]::User, - [parameter(ValueFromRemainingArguments = $true)][Object[]] $ignoredArguments -) - - Write-FunctionCallLogMessage -Invocation $MyInvocation -Parameters $PSBoundParameters - ## Called from chocolateysetup.psm1 - wrap any Write-Host in try/catch - - if ($variableType -eq [System.EnvironmentVariableTarget]::Machine) { - if (Test-ProcessAdminRights) { - Set-EnvironmentVariable -Name $variableName -Value $variableValue -Scope $variableType - } else { - $psArgs = "Install-ChocolateyEnvironmentVariable -variableName `'$variableName`' -variableValue `'$variableValue`' -variableType `'$variableType`'" - Start-ChocolateyProcessAsAdmin "$psArgs" + param( + [parameter(Mandatory = $false, Position = 0)][string] $variableName, + [parameter(Mandatory = $false, Position = 1)][string] $variableValue, + [parameter(Mandatory = $false, Position = 2)] + [System.EnvironmentVariableTarget] $variableType = [System.EnvironmentVariableTarget]::User, + [parameter(ValueFromRemainingArguments = $true)][Object[]] $ignoredArguments + ) + + Write-FunctionCallLogMessage -Invocation $MyInvocation -Parameters $PSBoundParameters + ## Called from chocolateysetup.psm1 - wrap any Write-Host in try/catch + + if ($variableType -eq [System.EnvironmentVariableTarget]::Machine) { + if (Test-ProcessAdminRights) { + Set-EnvironmentVariable -Name $variableName -Value $variableValue -Scope $variableType + } + else { + $psArgs = "Install-ChocolateyEnvironmentVariable -variableName `'$variableName`' -variableValue `'$variableValue`' -variableType `'$variableType`'" + Start-ChocolateyProcessAsAdmin "$psArgs" + } } - } else { - try { - Set-EnvironmentVariable -Name $variableName -Value $variableValue -Scope $variableType - } catch { - if (Test-ProcessAdminRights) { - # HKCU:\Environment may not exist, which happens sometimes with Server Core - Set-EnvironmentVariable -Name $variableName -Value $variableValue -Scope Machine - } else { - throw $_.Exception - } + else { + try { + Set-EnvironmentVariable -Name $variableName -Value $variableValue -Scope $variableType + } + catch { + if (Test-ProcessAdminRights) { + # HKCU:\Environment may not exist, which happens sometimes with Server Core + Set-EnvironmentVariable -Name $variableName -Value $variableValue -Scope Machine + } + else { + throw $_.Exception + } + } } - } - Set-Content env:\$variableName $variableValue + Set-Content env:\$variableName $variableValue } diff --git a/src/chocolatey.resources/helpers/functions/Install-ChocolateyExplorerMenuItem.ps1 b/src/chocolatey.resources/helpers/functions/Install-ChocolateyExplorerMenuItem.ps1 index d0c2185879..257c8521fb 100644 --- a/src/chocolatey.resources/helpers/functions/Install-ChocolateyExplorerMenuItem.ps1 +++ b/src/chocolatey.resources/helpers/functions/Install-ChocolateyExplorerMenuItem.ps1 @@ -15,7 +15,7 @@ # limitations under the License. function Install-ChocolateyExplorerMenuItem { -<# + <# .SYNOPSIS **NOTE:** Administrative Access Required. @@ -81,20 +81,28 @@ Install-ChocolateyExplorerMenuItem "sublime" "Open with Sublime Text 2" $sublime .LINK Install-ChocolateyShortcut #> -param( - [parameter(Mandatory=$true, Position=0)][string] $menuKey, - [parameter(Mandatory=$false, Position=1)][string] $menuLabel, - [parameter(Mandatory=$false, Position=2)][string] $command, - [parameter(Mandatory=$false, Position=3)] - [ValidateSet('file','directory')][string] $type = "file", - [parameter(ValueFromRemainingArguments = $true)][Object[]] $ignoredArguments -) -try { - - Write-FunctionCallLogMessage -Invocation $MyInvocation -Parameters $PSBoundParameters - - if($type -eq "file") {$key = "*"} elseif($type -eq "directory") {$key="directory"} else{ return 1} - $elevated = "` + param( + [parameter(Mandatory = $true, Position = 0)][string] $menuKey, + [parameter(Mandatory = $false, Position = 1)][string] $menuLabel, + [parameter(Mandatory = $false, Position = 2)][string] $command, + [parameter(Mandatory = $false, Position = 3)] + [ValidateSet('file', 'directory')][string] $type = "file", + [parameter(ValueFromRemainingArguments = $true)][Object[]] $ignoredArguments + ) + try { + + Write-FunctionCallLogMessage -Invocation $MyInvocation -Parameters $PSBoundParameters + + if ($type -eq "file") { + $key = "*" + } + elseif ($type -eq "directory") { + $key = "directory" + } + else { + return 1 + } + $elevated = "` if( -not (Test-Path -path HKCR:) ) {New-PSDrive -Name HKCR -PSProvider registry -Root Hkey_Classes_Root};` if(!(test-path -LiteralPath 'HKCR:\$key\shell\$menuKey')) { new-item -Path 'HKCR:\$key\shell\$menuKey' };` Set-ItemProperty -LiteralPath 'HKCR:\$key\shell\$menuKey' -Name '(Default)' -Value '$menuLabel';` @@ -102,11 +110,11 @@ try { Set-ItemProperty -LiteralPath 'HKCR:\$key\shell\$menuKey\command' -Name '(Default)' -Value '$command \`"%1\`"';` return 0;" - Start-ChocolateyProcessAsAdmin $elevated - Write-Host "'$menuKey' explorer menu item has been created" -} -catch { - $errorMessage = "'$menuKey' explorer menu item was not created - $($_.Exception.Message)" - Write-Warning $errorMessage - } + Start-ChocolateyProcessAsAdmin $elevated + Write-Host "'$menuKey' explorer menu item has been created" + } + catch { + $errorMessage = "'$menuKey' explorer menu item was not created - $($_.Exception.Message)" + Write-Warning $errorMessage + } } diff --git a/src/chocolatey.resources/helpers/functions/Install-ChocolateyFileAssociation.ps1 b/src/chocolatey.resources/helpers/functions/Install-ChocolateyFileAssociation.ps1 index d4786fdeae..6470b772e6 100644 --- a/src/chocolatey.resources/helpers/functions/Install-ChocolateyFileAssociation.ps1 +++ b/src/chocolatey.resources/helpers/functions/Install-ChocolateyFileAssociation.ps1 @@ -15,7 +15,7 @@ # limitations under the License. function Install-ChocolateyFileAssociation { -<# + <# .SYNOPSIS **NOTE:** Administrative Access Required. @@ -54,31 +54,31 @@ $sublimeExe = "$sublimeDir\tools\sublime_text.exe" Install-ChocolateyFileAssociation ".txt" $sublimeExe #> -param( - [parameter(Mandatory=$true, Position=0)][string] $extension, - [parameter(Mandatory=$true, Position=1)][string] $executable, - [parameter(ValueFromRemainingArguments = $true)][Object[]] $ignoredArguments -) + param( + [parameter(Mandatory = $true, Position = 0)][string] $extension, + [parameter(Mandatory = $true, Position = 1)][string] $executable, + [parameter(ValueFromRemainingArguments = $true)][Object[]] $ignoredArguments + ) - Write-FunctionCallLogMessage -Invocation $MyInvocation -Parameters $PSBoundParameters + Write-FunctionCallLogMessage -Invocation $MyInvocation -Parameters $PSBoundParameters - if(-not(Test-Path $executable)){ - $errorMessage = "`'$executable`' does not exist, not able to create association" - Write-Error $errorMessage - throw $errorMessage - } - $extension=$extension.trim() - if(-not($extension.StartsWith("."))) { - $extension = ".$extension" - } - $fileType = Split-Path $executable -leaf - $fileType = $fileType.Replace(" ","_") - $elevated = @" + if (-not(Test-Path $executable)) { + $errorMessage = "`'$executable`' does not exist, not able to create association" + Write-Error $errorMessage + throw $errorMessage + } + $extension = $extension.trim() + if (-not($extension.StartsWith("."))) { + $extension = ".$extension" + } + $fileType = Split-Path $executable -Leaf + $fileType = $fileType.Replace(" ", "_") + $elevated = @" cmd /c "assoc $extension=$fileType" cmd /c 'ftype $fileType="$executable" "%1" "%*"' New-PSDrive -Name HKCR -PSProvider Registry -Root HKEY_CLASSES_ROOT Set-ItemProperty -Path "HKCR:\$fileType" -Name "(Default)" -Value "$fileType file" -ErrorAction Stop "@ - Start-ChocolateyProcessAsAdmin $elevated - Write-Host "`'$extension`' has been associated with `'$executable`'" + Start-ChocolateyProcessAsAdmin $elevated + Write-Host "`'$extension`' has been associated with `'$executable`'" } diff --git a/src/chocolatey.resources/helpers/functions/Install-ChocolateyInstallPackage.ps1 b/src/chocolatey.resources/helpers/functions/Install-ChocolateyInstallPackage.ps1 index c3ee1b9af3..7376cac3b8 100644 --- a/src/chocolatey.resources/helpers/functions/Install-ChocolateyInstallPackage.ps1 +++ b/src/chocolatey.resources/helpers/functions/Install-ChocolateyInstallPackage.ps1 @@ -15,7 +15,7 @@ # limitations under the License. function Install-ChocolateyInstallPackage { - <# + <# .SYNOPSIS **NOTE:** Administrative Access Required. @@ -210,167 +210,175 @@ Get-UninstallRegistryKey .LINK Start-ChocolateyProcessAsAdmin #> - param( - [parameter(Mandatory = $true, Position = 0)][string] $packageName, - [parameter(Mandatory = $false, Position = 1)] - [alias("installerType", "installType")][string] $fileType = 'exe', - [parameter(Mandatory = $false, Position = 2)][string[]] $silentArgs = '', - [alias("fileFullPath")][parameter(Mandatory = $false, Position = 3)][string] $file, - [alias("fileFullPath64")][parameter(Mandatory = $false)][string] $file64, - [parameter(Mandatory = $false)] $validExitCodes = @(0), - [parameter(Mandatory = $false)] - [alias("useOnlyPackageSilentArgs")][switch] $useOnlyPackageSilentArguments = $false, - [parameter(ValueFromRemainingArguments = $true)][Object[]] $ignoredArguments - ) - [string]$silentArgs = $silentArgs -join ' ' - - Write-FunctionCallLogMessage -Invocation $MyInvocation -Parameters $PSBoundParameters - - $bitnessMessage = '' - $fileFullPath = $file - if ((Get-OSArchitectureWidth 32) -or $env:ChocolateyForceX86 -eq 'true') { - if (!$file) { throw "32-bit installation is not supported for $packageName"; } - if ($file64) { $bitnessMessage = '32-bit '; } - } - elseif ($file64) { - $fileFullPath = $file64 - $bitnessMessage = '64-bit ' - } - - if ($fileFullPath -eq '' -or $fileFullPath -eq $null) { - throw 'Package parameters incorrect, either File or File64 must be specified.' - } - - Write-Host "Installing $bitnessMessage$packageName..." - - if ($fileType -eq '' -or $fileType -eq $null) { - Write-Debug 'No FileType supplied. Using the file extension to determine FileType' - $fileType = [System.IO.Path]::GetExtension("$fileFullPath").Replace(".", "") - } - - $installerTypeLower = $fileType.ToLower() - if ('msi', 'exe', 'msu', 'msp' -notcontains $installerTypeLower) { - Write-Warning "FileType '$fileType' is unrecognized, using 'exe' instead." - $fileType = 'exe' - } - - $env:ChocolateyInstallerType = $fileType - - $additionalInstallArgs = $env:chocolateyInstallArguments; - if ($additionalInstallArgs -eq $null) { - $additionalInstallArgs = ''; - } - else { - #Use a Regex Or ('|') to do the match, instead of multiple '-or' clauses - $argPattern = @( - 'INSTALLDIR' - 'TARGETDIR' - 'dir\=' - '\/D\=' - ) -join '|' - - if ($additionalInstallArgs -match $argPattern) { - @" + param( + [parameter(Mandatory = $true, Position = 0)][string] $packageName, + [parameter(Mandatory = $false, Position = 1)] + [alias("installerType", "installType")][string] $fileType = 'exe', + [parameter(Mandatory = $false, Position = 2)][string[]] $silentArgs = '', + [alias("fileFullPath")][parameter(Mandatory = $false, Position = 3)][string] $file, + [alias("fileFullPath64")][parameter(Mandatory = $false)][string] $file64, + [parameter(Mandatory = $false)] $validExitCodes = @(0), + [parameter(Mandatory = $false)] + [alias("useOnlyPackageSilentArgs")][switch] $useOnlyPackageSilentArguments = $false, + [parameter(ValueFromRemainingArguments = $true)][Object[]] $ignoredArguments + ) + [string]$silentArgs = $silentArgs -join ' ' + + Write-FunctionCallLogMessage -Invocation $MyInvocation -Parameters $PSBoundParameters + + $bitnessMessage = '' + $fileFullPath = $file + if ((Get-OSArchitectureWidth 32) -or $env:ChocolateyForceX86 -eq 'true') { + if (!$file) { + throw "32-bit installation is not supported for $packageName"; + } + if ($file64) { + $bitnessMessage = '32-bit '; + } + } + elseif ($file64) { + $fileFullPath = $file64 + $bitnessMessage = '64-bit ' + } + + if ($fileFullPath -eq '' -or $fileFullPath -eq $null) { + throw 'Package parameters incorrect, either File or File64 must be specified.' + } + + Write-Host "Installing $bitnessMessage$packageName..." + + if ($fileType -eq '' -or $fileType -eq $null) { + Write-Debug 'No FileType supplied. Using the file extension to determine FileType' + $fileType = [System.IO.Path]::GetExtension("$fileFullPath").Replace(".", "") + } + + $installerTypeLower = $fileType.ToLower() + if ('msi', 'exe', 'msu', 'msp' -notcontains $installerTypeLower) { + Write-Warning "FileType '$fileType' is unrecognized, using 'exe' instead." + $fileType = 'exe' + } + + $env:ChocolateyInstallerType = $fileType + + $additionalInstallArgs = $env:chocolateyInstallArguments; + if ($additionalInstallArgs -eq $null) { + $additionalInstallArgs = ''; + } + else { + #Use a Regex Or ('|') to do the match, instead of multiple '-or' clauses + $argPattern = @( + 'INSTALLDIR' + 'TARGETDIR' + 'dir\=' + '\/D\=' + ) -join '|' + + if ($additionalInstallArgs -match $argPattern) { + @" Pro / Business supports a single, ubiquitous install directory option. Stop the hassle of determining how to pass install directory overrides to install arguments for each package / installer type. Check out Pro / Business - https://chocolatey.org/compare" "@ | Write-Warning + } } - } - $overrideArguments = $env:chocolateyInstallOverride; - - # remove \chocolatey\chocolatey\ - # might be a slight issue here if the download path is the older - $silentArgs = $silentArgs -replace '\\chocolatey\\chocolatey\\', '\chocolatey\' - $additionalInstallArgs = $additionalInstallArgs -replace '\\chocolatey\\chocolatey\\', '\chocolatey\' - $updatedFilePath = $fileFullPath -replace '\\chocolatey\\chocolatey\\', '\chocolatey\' - if ([System.IO.File]::Exists($updatedFilePath)) { - $fileFullPath = $updatedFilePath - } - - $ignoreFile = $fileFullPath + '.ignore' - if ($env:ChocolateyInstall -and $ignoreFile -match [System.Text.RegularExpressions.Regex]::Escape($env:ChocolateyInstall)) { - try { - '' | out-file $ignoreFile + $overrideArguments = $env:chocolateyInstallOverride; + + # remove \chocolatey\chocolatey\ + # might be a slight issue here if the download path is the older + $silentArgs = $silentArgs -replace '\\chocolatey\\chocolatey\\', '\chocolatey\' + $additionalInstallArgs = $additionalInstallArgs -replace '\\chocolatey\\chocolatey\\', '\chocolatey\' + $updatedFilePath = $fileFullPath -replace '\\chocolatey\\chocolatey\\', '\chocolatey\' + if ([System.IO.File]::Exists($updatedFilePath)) { + $fileFullPath = $updatedFilePath } - catch { - Write-Warning "Unable to generate `'$ignoreFile`'" + + $ignoreFile = $fileFullPath + '.ignore' + if ($env:ChocolateyInstall -and $ignoreFile -match [System.Text.RegularExpressions.Regex]::Escape($env:ChocolateyInstall)) { + try { + '' | Out-File $ignoreFile + } + catch { + Write-Warning "Unable to generate `'$ignoreFile`'" + } } - } - - $workingDirectory = Get-Location -PSProvider "FileSystem" - try { - $workingDirectory = [System.IO.Path]::GetDirectoryName($fileFullPath) - } - catch { - Write-Warning "Unable to set the working directory for installer to location of '$fileFullPath'" - $workingDirectory = $env:TEMP - } - - try { - # make sure any logging folder exists - $pattern = "(?:['`"])([a-zA-Z]\:\\[^'`"]+)(?:[`"'])|([a-zA-Z]\:\\[\S]+)" - $silentArgs, $additionalInstallArgs | - ForEach-Object { Select-String $pattern -input $_ -AllMatches } | - ForEach-Object { $_.Matches } | ForEach-Object { - $argDirectory = $_.Groups[1] - if ($argDirectory -eq $null -or $argDirectory -eq '') { continue } - $argDirectory = [System.IO.Path]::GetFullPath([System.IO.Path]::GetDirectoryName($argDirectory)) - Write-Debug "Ensuring '$argDirectory' exists" - if (![System.IO.Directory]::Exists($argDirectory)) { [System.IO.Directory]::CreateDirectory($argDirectory) | Out-Null } - } - } - catch { - Write-Debug "Error ensuring directories exist - $($_.Exception.Message)" - } - - if ($fileType -like 'msi') { - $msiArgs = "/i `"$fileFullPath`"" - $msiArgs = if ($overrideArguments) { - Write-Host "Overriding package arguments with '$additionalInstallArgs' (replacing '$silentArgs')" - "$msiArgs $additionalInstallArgs" + + $workingDirectory = Get-Location -PSProvider "FileSystem" + try { + $workingDirectory = [System.IO.Path]::GetDirectoryName($fileFullPath) } - else { - "$msiArgs $silentArgs $additionalInstallArgs" + catch { + Write-Warning "Unable to set the working directory for installer to location of '$fileFullPath'" + $workingDirectory = $env:TEMP } - $env:ChocolateyExitCode = Start-ChocolateyProcessAsAdmin "$msiArgs" "$($env:SystemRoot)\System32\msiexec.exe" -validExitCodes $validExitCodes -workingDirectory $workingDirectory - } - - if ($fileType -like 'msp') { - $msiArgs = '/update "{0}"' -f $fileFullPath - if ($overrideArguments) { - Write-Host "Overriding package arguments with '$additionalInstallArgs' (replacing '$silentArgs')"; - $msiArgs = "$msiArgs $additionalInstallArgs"; + try { + # make sure any logging folder exists + $pattern = "(?:['`"])([a-zA-Z]\:\\[^'`"]+)(?:[`"'])|([a-zA-Z]\:\\[\S]+)" + $silentArgs, $additionalInstallArgs | + ForEach-Object { Select-String $pattern -input $_ -AllMatches } | + ForEach-Object { $_.Matches } | ForEach-Object { + $argDirectory = $_.Groups[1] + if ($argDirectory -eq $null -or $argDirectory -eq '') { + continue + } + $argDirectory = [System.IO.Path]::GetFullPath([System.IO.Path]::GetDirectoryName($argDirectory)) + Write-Debug "Ensuring '$argDirectory' exists" + if (![System.IO.Directory]::Exists($argDirectory)) { + [System.IO.Directory]::CreateDirectory($argDirectory) | Out-Null + } + } } - else { - $msiArgs = "$msiArgs $silentArgs $additionalInstallArgs"; + catch { + Write-Debug "Error ensuring directories exist - $($_.Exception.Message)" } - $env:ChocolateyExitCode = Start-ChocolateyProcessAsAdmin "$msiArgs" "$($env:SystemRoot)\System32\msiexec.exe" -validExitCodes $validExitCodes -workingDirectory $workingDirectory - } - - if ($fileType -like 'exe') { - if ($overrideArguments) { - Write-Host "Overriding package arguments with '$additionalInstallArgs' (replacing '$silentArgs')"; - $env:ChocolateyExitCode = Start-ChocolateyProcessAsAdmin "$additionalInstallArgs" $fileFullPath -validExitCodes $validExitCodes -workingDirectory $workingDirectory + if ($fileType -like 'msi') { + $msiArgs = "/i `"$fileFullPath`"" + $msiArgs = if ($overrideArguments) { + Write-Host "Overriding package arguments with '$additionalInstallArgs' (replacing '$silentArgs')" + "$msiArgs $additionalInstallArgs" + } + else { + "$msiArgs $silentArgs $additionalInstallArgs" + } + + $env:ChocolateyExitCode = Start-ChocolateyProcessAsAdmin "$msiArgs" "$($env:SystemRoot)\System32\msiexec.exe" -validExitCodes $validExitCodes -workingDirectory $workingDirectory } - else { - $env:ChocolateyExitCode = Start-ChocolateyProcessAsAdmin "$silentArgs $additionalInstallArgs" $fileFullPath -validExitCodes $validExitCodes -workingDirectory $workingDirectory + + if ($fileType -like 'msp') { + $msiArgs = '/update "{0}"' -f $fileFullPath + if ($overrideArguments) { + Write-Host "Overriding package arguments with '$additionalInstallArgs' (replacing '$silentArgs')"; + $msiArgs = "$msiArgs $additionalInstallArgs"; + } + else { + $msiArgs = "$msiArgs $silentArgs $additionalInstallArgs"; + } + + $env:ChocolateyExitCode = Start-ChocolateyProcessAsAdmin "$msiArgs" "$($env:SystemRoot)\System32\msiexec.exe" -validExitCodes $validExitCodes -workingDirectory $workingDirectory } - } - if ($fileType -like 'msu') { - if ($overrideArguments) { - Write-Host "Overriding package arguments with '$additionalInstallArgs' (replacing '$silentArgs')"; - $msuArgs = "`"$fileFullPath`" $additionalInstallArgs" + if ($fileType -like 'exe') { + if ($overrideArguments) { + Write-Host "Overriding package arguments with '$additionalInstallArgs' (replacing '$silentArgs')"; + $env:ChocolateyExitCode = Start-ChocolateyProcessAsAdmin "$additionalInstallArgs" $fileFullPath -validExitCodes $validExitCodes -workingDirectory $workingDirectory + } + else { + $env:ChocolateyExitCode = Start-ChocolateyProcessAsAdmin "$silentArgs $additionalInstallArgs" $fileFullPath -validExitCodes $validExitCodes -workingDirectory $workingDirectory + } } - else { - $msuArgs = "`"$fileFullPath`" $silentArgs $additionalInstallArgs" + + if ($fileType -like 'msu') { + if ($overrideArguments) { + Write-Host "Overriding package arguments with '$additionalInstallArgs' (replacing '$silentArgs')"; + $msuArgs = "`"$fileFullPath`" $additionalInstallArgs" + } + else { + $msuArgs = "`"$fileFullPath`" $silentArgs $additionalInstallArgs" + } + $env:ChocolateyExitCode = Start-ChocolateyProcessAsAdmin "$msuArgs" "$($env:SystemRoot)\System32\wusa.exe" -validExitCodes $validExitCodes -workingDirectory $workingDirectory } - $env:ChocolateyExitCode = Start-ChocolateyProcessAsAdmin "$msuArgs" "$($env:SystemRoot)\System32\wusa.exe" -validExitCodes $validExitCodes -workingDirectory $workingDirectory - } - Write-Host "$packageName has been installed." + Write-Host "$packageName has been installed." } diff --git a/src/chocolatey.resources/helpers/functions/Install-ChocolateyPackage.ps1 b/src/chocolatey.resources/helpers/functions/Install-ChocolateyPackage.ps1 index c0629760df..8e03bb999c 100644 --- a/src/chocolatey.resources/helpers/functions/Install-ChocolateyPackage.ps1 +++ b/src/chocolatey.resources/helpers/functions/Install-ChocolateyPackage.ps1 @@ -15,7 +15,7 @@ # limitations under the License. function Install-ChocolateyPackage { -<# + <# .SYNOPSIS **NOTE:** Administrative Access Required. @@ -224,7 +224,7 @@ Allows splatting with arguments that do not apply. Do not use directly. Specifies the commands to run after download has completed but before install steps have begun. Available in 0.11.0+. -Use this for starting an auxiliary process such as AutoHotkey, so that any timeouts are not +Use this for starting an auxiliary process such as AutoHotkey, so that any timeouts are not affected by the time to download. .EXAMPLE @@ -345,80 +345,86 @@ Get-UninstallRegistryKey .LINK Install-ChocolateyZipPackage #> -param( - [parameter(Mandatory=$true, Position=0)][string] $packageName, - [parameter(Mandatory=$false, Position=1)] - [alias("installerType","installType")][string] $fileType = 'exe', - [parameter(Mandatory=$false, Position=2)][string[]] $silentArgs = '', - [parameter(Mandatory=$false, Position=3)][string] $url = '', - [parameter(Mandatory=$false, Position=4)] - [alias("url64")][string] $url64bit = '', - [parameter(Mandatory=$false)] $validExitCodes = @(0), - [parameter(Mandatory=$false)][string] $checksum = '', - [parameter(Mandatory=$false)][string] $checksumType = '', - [parameter(Mandatory=$false)][string] $checksum64 = '', - [parameter(Mandatory=$false)][string] $checksumType64 = '', - [parameter(Mandatory=$false)][hashtable] $options = @{Headers=@{}}, - [alias("fileFullPath")][parameter(Mandatory=$false)][string] $file = '', - [alias("fileFullPath64")][parameter(Mandatory=$false)][string] $file64 = '', - [parameter(Mandatory=$false)] - [alias("useOnlyPackageSilentArgs")][switch] $useOnlyPackageSilentArguments = $false, - [parameter(Mandatory=$false)][switch]$useOriginalLocation, - [parameter(Mandatory=$false)][scriptblock] $beforeInstall, - [parameter(ValueFromRemainingArguments = $true)][Object[]] $ignoredArguments -) - [string]$silentArgs = $silentArgs -join ' ' - - Write-FunctionCallLogMessage -Invocation $MyInvocation -Parameters $PSBoundParameters - - $chocoTempDir = $env:TEMP - $tempDir = Join-Path $chocoTempDir "$($env:chocolateyPackageName)" - if ($env:chocolateyPackageVersion -ne $null) { $tempDir = Join-Path $tempDir "$($env:chocolateyPackageVersion)"; } - $tempDir = $tempDir -replace '\\chocolatey\\chocolatey\\', '\chocolatey\' - if (![System.IO.Directory]::Exists($tempDir)) { [System.IO.Directory]::CreateDirectory($tempDir) | Out-Null } - $downloadFilePath = Join-Path $tempDir "$($packageName)Install.$fileType" - - if ($url -eq '' -or $url -eq $null) { - $url = $file - } - if ($url64bit -eq '' -or $url64bit -eq $null) { - $url64bit = $file64 - } + param( + [parameter(Mandatory = $true, Position = 0)][string] $packageName, + [parameter(Mandatory = $false, Position = 1)] + [alias("installerType", "installType")][string] $fileType = 'exe', + [parameter(Mandatory = $false, Position = 2)][string[]] $silentArgs = '', + [parameter(Mandatory = $false, Position = 3)][string] $url = '', + [parameter(Mandatory = $false, Position = 4)] + [alias("url64")][string] $url64bit = '', + [parameter(Mandatory = $false)] $validExitCodes = @(0), + [parameter(Mandatory = $false)][string] $checksum = '', + [parameter(Mandatory = $false)][string] $checksumType = '', + [parameter(Mandatory = $false)][string] $checksum64 = '', + [parameter(Mandatory = $false)][string] $checksumType64 = '', + [parameter(Mandatory = $false)][hashtable] $options = @{Headers = @{} }, + [alias("fileFullPath")][parameter(Mandatory = $false)][string] $file = '', + [alias("fileFullPath64")][parameter(Mandatory = $false)][string] $file64 = '', + [parameter(Mandatory = $false)] + [alias("useOnlyPackageSilentArgs")][switch] $useOnlyPackageSilentArguments = $false, + [parameter(Mandatory = $false)][switch]$useOriginalLocation, + [parameter(Mandatory = $false)][scriptblock] $beforeInstall, + [parameter(ValueFromRemainingArguments = $true)][Object[]] $ignoredArguments + ) + [string]$silentArgs = $silentArgs -join ' ' + + Write-FunctionCallLogMessage -Invocation $MyInvocation -Parameters $PSBoundParameters + + $chocoTempDir = $env:TEMP + $tempDir = Join-Path $chocoTempDir "$($env:chocolateyPackageName)" + if ($env:chocolateyPackageVersion -ne $null) { + $tempDir = Join-Path $tempDir "$($env:chocolateyPackageVersion)"; + } + $tempDir = $tempDir -replace '\\chocolatey\\chocolatey\\', '\chocolatey\' + if (![System.IO.Directory]::Exists($tempDir)) { + [System.IO.Directory]::CreateDirectory($tempDir) | Out-Null + } + $downloadFilePath = Join-Path $tempDir "$($packageName)Install.$fileType" - [string]$filePath = $downloadFilePath - if ($useOriginalLocation) { - $filePath = $url - if (Get-OSArchitectureWidth 64) { - $forceX86 = $env:chocolateyForceX86 - if ($forceX86) { - Write-Debug "User specified '-x86' so forcing 32-bit" - } else { - if ($url64bit -ne $null -and $url64bit -ne '') { - $filePath = $url64bit + if ($url -eq '' -or $url -eq $null) { + $url = $file + } + if ($url64bit -eq '' -or $url64bit -eq $null) { + $url64bit = $file64 + } + + [string]$filePath = $downloadFilePath + if ($useOriginalLocation) { + $filePath = $url + if (Get-OSArchitectureWidth 64) { + $forceX86 = $env:chocolateyForceX86 + if ($forceX86) { + Write-Debug "User specified '-x86' so forcing 32-bit" + } + else { + if ($url64bit -ne $null -and $url64bit -ne '') { + $filePath = $url64bit + } + } } - } } - } else { - $filePath = Get-ChocolateyWebFile -PackageName $packageName ` - -FileFullPath $downloadFilePath ` - -Url $url ` - -Url64bit $url64bit ` - -Checksum $checksum ` - -ChecksumType $checksumType ` - -Checksum64 $checksum64 ` - -ChecksumType64 $checksumType64 ` - -Options $options ` - -GetOriginalFileName - } + else { + $filePath = Get-ChocolateyWebFile -PackageName $packageName ` + -FileFullPath $downloadFilePath ` + -Url $url ` + -Url64bit $url64bit ` + -Checksum $checksum ` + -ChecksumType $checksumType ` + -Checksum64 $checksum64 ` + -ChecksumType64 $checksumType64 ` + -Options $options ` + -GetOriginalFileName + } - if ($beforeInstall) { - & $beforeInstall - } + if ($beforeInstall) { + & $beforeInstall + } - Install-ChocolateyInstallPackage -PackageName $packageName ` - -FileType $fileType ` - -SilentArgs $silentArgs ` - -File $filePath ` - -ValidExitCodes $validExitCodes ` - -UseOnlyPackageSilentArguments:$useOnlyPackageSilentArguments + Install-ChocolateyInstallPackage -packageName $packageName ` + -fileType $fileType ` + -silentArgs $silentArgs ` + -file $filePath ` + -validExitCodes $validExitCodes ` + -UseOnlyPackageSilentArguments:$useOnlyPackageSilentArguments } diff --git a/src/chocolatey.resources/helpers/functions/Install-ChocolateyPath.ps1 b/src/chocolatey.resources/helpers/functions/Install-ChocolateyPath.ps1 index faeaee8585..efcd967161 100644 --- a/src/chocolatey.resources/helpers/functions/Install-ChocolateyPath.ps1 +++ b/src/chocolatey.resources/helpers/functions/Install-ChocolateyPath.ps1 @@ -15,7 +15,7 @@ # limitations under the License. function Install-ChocolateyPath { -<# + <# .SYNOPSIS **NOTE:** Administrative Access Required when `-PathType 'Machine'.` @@ -66,53 +66,59 @@ Set-EnvironmentVariable .LINK Get-ToolsLocation #> -param( - [parameter(Mandatory=$true, Position=0)][string] $pathToInstall, - [parameter(Mandatory=$false, Position=1)][System.EnvironmentVariableTarget] $pathType = [System.EnvironmentVariableTarget]::User, - [parameter(ValueFromRemainingArguments = $true)][Object[]] $ignoredArguments -) - - Write-FunctionCallLogMessage -Invocation $MyInvocation -Parameters $PSBoundParameters - ## Called from chocolateysetup.psm1 - wrap any Write-Host in try/catch - - $originalPathToInstall = $pathToInstall - - #get the PATH variable - Update-SessionEnvironment - $envPath = $env:PATH - if (!$envPath.ToLower().Contains($pathToInstall.ToLower())) - { - try { - Write-Host "PATH environment variable does not have $pathToInstall in it. Adding..." - } catch { - Write-Verbose "PATH environment variable does not have $pathToInstall in it. Adding..." + param( + [parameter(Mandatory = $true, Position = 0)][string] $pathToInstall, + [parameter(Mandatory = $false, Position = 1)][System.EnvironmentVariableTarget] $pathType = [System.EnvironmentVariableTarget]::User, + [parameter(ValueFromRemainingArguments = $true)][Object[]] $ignoredArguments + ) + + Write-FunctionCallLogMessage -Invocation $MyInvocation -Parameters $PSBoundParameters + ## Called from chocolateysetup.psm1 - wrap any Write-Host in try/catch + + $originalPathToInstall = $pathToInstall + + #get the PATH variable + Update-SessionEnvironment + $envPath = $env:PATH + if (!$envPath.ToLower().Contains($pathToInstall.ToLower())) { + try { + Write-Host "PATH environment variable does not have $pathToInstall in it. Adding..." + } + catch { + Write-Verbose "PATH environment variable does not have $pathToInstall in it. Adding..." + } + + $actualPath = Get-EnvironmentVariable -Name 'Path' -Scope $pathType -PreserveVariables + + $statementTerminator = ";" + #does the path end in ';'? + $hasStatementTerminator = $actualPath -ne $null -and $actualPath.EndsWith($statementTerminator) + # if the last digit is not ;, then we are adding it + If (!$hasStatementTerminator -and $actualPath -ne $null) { + $pathToInstall = $statementTerminator + $pathToInstall + } + if (!$pathToInstall.EndsWith($statementTerminator)) { + $pathToInstall = $pathToInstall + $statementTerminator + } + $actualPath = $actualPath + $pathToInstall + + if ($pathType -eq [System.EnvironmentVariableTarget]::Machine) { + if (Test-ProcessAdminRights) { + Set-EnvironmentVariable -Name 'Path' -Value $actualPath -Scope $pathType + } + else { + $psArgs = "Install-ChocolateyPath -pathToInstall `'$originalPathToInstall`' -pathType `'$pathType`'" + Start-ChocolateyProcessAsAdmin "$psArgs" + } + } + else { + Set-EnvironmentVariable -Name 'Path' -Value $actualPath -Scope $pathType + } + + #add it to the local path as well so users will be off and running + $envPSPath = $env:PATH + $env:Path = $envPSPath + $statementTerminator + $pathToInstall } - - $actualPath = Get-EnvironmentVariable -Name 'Path' -Scope $pathType -PreserveVariables - - $statementTerminator = ";" - #does the path end in ';'? - $hasStatementTerminator = $actualPath -ne $null -and $actualPath.EndsWith($statementTerminator) - # if the last digit is not ;, then we are adding it - If (!$hasStatementTerminator -and $actualPath -ne $null) {$pathToInstall = $statementTerminator + $pathToInstall} - if (!$pathToInstall.EndsWith($statementTerminator)) {$pathToInstall = $pathToInstall + $statementTerminator} - $actualPath = $actualPath + $pathToInstall - - if ($pathType -eq [System.EnvironmentVariableTarget]::Machine) { - if (Test-ProcessAdminRights) { - Set-EnvironmentVariable -Name 'Path' -Value $actualPath -Scope $pathType - } else { - $psArgs = "Install-ChocolateyPath -pathToInstall `'$originalPathToInstall`' -pathType `'$pathType`'" - Start-ChocolateyProcessAsAdmin "$psArgs" - } - } else { - Set-EnvironmentVariable -Name 'Path' -Value $actualPath -Scope $pathType - } - - #add it to the local path as well so users will be off and running - $envPSPath = $env:PATH - $env:Path = $envPSPath + $statementTerminator + $pathToInstall - } } # [System.Text.RegularExpressions.Regex]::Match($Path,[System.Text.RegularExpressions.Regex]::Escape('locationtoMatch') + '(?>;)?', '', [System.Text.RegularExpressions.RegexOptions]::IgnoreCase) diff --git a/src/chocolatey.resources/helpers/functions/Install-ChocolateyPinnedTaskBarItem.ps1 b/src/chocolatey.resources/helpers/functions/Install-ChocolateyPinnedTaskBarItem.ps1 index 032e585ea1..cd8ae15344 100644 --- a/src/chocolatey.resources/helpers/functions/Install-ChocolateyPinnedTaskBarItem.ps1 +++ b/src/chocolatey.resources/helpers/functions/Install-ChocolateyPinnedTaskBarItem.ps1 @@ -15,7 +15,7 @@ # limitations under the License. function Install-ChocolateyPinnedTaskBarItem { -<# + <# .SYNOPSIS Creates an item in the task bar linking to the provided path. @@ -47,35 +47,38 @@ Install-ChocolateyShortcut .LINK Install-ChocolateyExplorerMenuItem #> -param( - [parameter(Mandatory=$true, Position=0)][string] $targetFilePath, - [parameter(ValueFromRemainingArguments = $true)][Object[]]$ignoredArguments -) + param( + [parameter(Mandatory = $true, Position = 0)][string] $targetFilePath, + [parameter(ValueFromRemainingArguments = $true)][Object[]]$ignoredArguments + ) - Write-FunctionCallLogMessage -Invocation $MyInvocation -Parameters $PSBoundParameters - - try{ - if (test-path($targetFilePath)) { - $verb = "Pin To Taskbar" - $path= split-path $targetFilePath - $shell=new-object -com "Shell.Application" - $folder=$shell.Namespace($path) - $item = $folder.Parsename((split-path $targetFilePath -leaf)) - $itemVerb = $item.Verbs() | Where-Object {$_.Name.Replace("&","") -eq $verb} - if($itemVerb -eq $null){ - Write-Host "TaskBar verb not found for $item. It may have already been pinned" - } else { - $itemVerb.DoIt() - } - Write-Host "`'$targetFilePath`' has been pinned to the task bar on your desktop" - } else { - $errorMessage = "`'$targetFilePath`' does not exist, not able to pin to task bar" - } + Write-FunctionCallLogMessage -Invocation $MyInvocation -Parameters $PSBoundParameters - if ($errorMessage) { - Write-Warning $errorMessage - } - } catch { - Write-Warning "Unable to create pin. Error captured was $($_.Exception.Message)." - } + try { + if (Test-Path($targetFilePath)) { + $verb = "Pin To Taskbar" + $path = Split-Path $targetFilePath + $shell = New-Object -com "Shell.Application" + $folder = $shell.Namespace($path) + $item = $folder.Parsename((Split-Path $targetFilePath -Leaf)) + $itemVerb = $item.Verbs() | Where-Object { $_.Name.Replace("&", "") -eq $verb } + if ($itemVerb -eq $null) { + Write-Host "TaskBar verb not found for $item. It may have already been pinned" + } + else { + $itemVerb.DoIt() + } + Write-Host "`'$targetFilePath`' has been pinned to the task bar on your desktop" + } + else { + $errorMessage = "`'$targetFilePath`' does not exist, not able to pin to task bar" + } + + if ($errorMessage) { + Write-Warning $errorMessage + } + } + catch { + Write-Warning "Unable to create pin. Error captured was $($_.Exception.Message)." + } } diff --git a/src/chocolatey.resources/helpers/functions/Install-ChocolateyPowershellCommand.ps1 b/src/chocolatey.resources/helpers/functions/Install-ChocolateyPowershellCommand.ps1 index d28ce2a1cc..eda1092614 100644 --- a/src/chocolatey.resources/helpers/functions/Install-ChocolateyPowershellCommand.ps1 +++ b/src/chocolatey.resources/helpers/functions/Install-ChocolateyPowershellCommand.ps1 @@ -15,7 +15,7 @@ # limitations under the License. function Install-ChocolateyPowershellCommand { -<# + <# .SYNOPSIS Installs a PowerShell Script as a command @@ -176,38 +176,37 @@ Install-ChocolateyPackage .LINK Install-ChocolateyZipPackage #> -param( - [parameter(Mandatory=$false, Position=0)][string] $packageName, - [alias("file","fileFullPath")][parameter(Mandatory=$true, Position=1)][string] $psFileFullPath, - [parameter(Mandatory=$false, Position=2)][string] $url ='', - [parameter(Mandatory=$false, Position=3)] - [alias("url64")][string] $url64bit = '', - [parameter(Mandatory=$false)][string] $checksum = '', - [parameter(Mandatory=$false)][string] $checksumType = '', - [parameter(Mandatory=$false)][string] $checksum64 = '', - [parameter(Mandatory=$false)][string] $checksumType64 = '', - [parameter(Mandatory=$false)][hashtable] $options = @{Headers=@{}}, - [parameter(ValueFromRemainingArguments = $true)][Object[]] $ignoredArguments -) - - Write-FunctionCallLogMessage -Invocation $MyInvocation -Parameters $PSBoundParameters - - if ($url -ne '') { - Get-ChocolateyWebFile $packageName $psFileFullPath $url $url64bit -checksum $checksum -checksumType $checksumType -checksum64 $checksum64 -checksumType64 $checksumType64 -Options $options - } - - if ($env:chocolateyPackageName -ne $null -and $env:chocolateyPackageName -eq $env:ChocolateyInstallDirectoryPackage) { - Write-Warning "Install Directory override not available for PowerShell command packages." - } - - $nugetPath = $(Split-Path -parent $helpersPath) - $nugetExePath = Join-Path $nuGetPath 'bin' - - $cmdName = [System.IO.Path]::GetFileNameWithoutExtension($psFileFullPath) - $packageBatchFileName = Join-Path $nugetExePath "$($cmdName).bat" - - Write-Host "Adding $packageBatchFileName and pointing it to powershell command $psFileFullPath" -"@echo off -powershell -NoProfile -ExecutionPolicy unrestricted -Command ""& `'$psFileFullPath`' %*"""| Out-File $packageBatchFileName -encoding ASCII - + param( + [parameter(Mandatory = $false, Position = 0)][string] $packageName, + [alias("file", "fileFullPath")][parameter(Mandatory = $true, Position = 1)][string] $psFileFullPath, + [parameter(Mandatory = $false, Position = 2)][string] $url = '', + [parameter(Mandatory = $false, Position = 3)] + [alias("url64")][string] $url64bit = '', + [parameter(Mandatory = $false)][string] $checksum = '', + [parameter(Mandatory = $false)][string] $checksumType = '', + [parameter(Mandatory = $false)][string] $checksum64 = '', + [parameter(Mandatory = $false)][string] $checksumType64 = '', + [parameter(Mandatory = $false)][hashtable] $options = @{Headers = @{} }, + [parameter(ValueFromRemainingArguments = $true)][Object[]] $ignoredArguments + ) + + Write-FunctionCallLogMessage -Invocation $MyInvocation -Parameters $PSBoundParameters + + if ($url -ne '') { + Get-ChocolateyWebFile $packageName $psFileFullPath $url $url64bit -checksum $checksum -checksumType $checksumType -checksum64 $checksum64 -checksumType64 $checksumType64 -Options $options + } + + if ($env:chocolateyPackageName -ne $null -and $env:chocolateyPackageName -eq $env:ChocolateyInstallDirectoryPackage) { + Write-Warning "Install Directory override not available for PowerShell command packages." + } + + $nugetPath = $(Split-Path -Parent $helpersPath) + $nugetExePath = Join-Path $nuGetPath 'bin' + + $cmdName = [System.IO.Path]::GetFileNameWithoutExtension($psFileFullPath) + $packageBatchFileName = Join-Path $nugetExePath "$($cmdName).bat" + + Write-Host "Adding $packageBatchFileName and pointing it to powershell command $psFileFullPath" + "@echo off +powershell -NoProfile -ExecutionPolicy unrestricted -Command ""& `'$psFileFullPath`' %*"""| Out-File $packageBatchFileName -Encoding ASCII } diff --git a/src/chocolatey.resources/helpers/functions/Install-ChocolateyShortcut.ps1 b/src/chocolatey.resources/helpers/functions/Install-ChocolateyShortcut.ps1 index d5d1f84f8b..f45a587471 100644 --- a/src/chocolatey.resources/helpers/functions/Install-ChocolateyShortcut.ps1 +++ b/src/chocolatey.resources/helpers/functions/Install-ChocolateyShortcut.ps1 @@ -15,7 +15,7 @@ # limitations under the License. function Install-ChocolateyShortcut { -<# + <# .SYNOPSIS Creates a shortcut @@ -116,109 +116,113 @@ Install-ChocolateyExplorerMenuItem .LINK Install-ChocolateyPinnedTaskBarItem #> - param( - [parameter(Mandatory=$true, Position=0)][string] $shortcutFilePath, - [parameter(Mandatory=$true, Position=1)][string] $targetPath, - [parameter(Mandatory=$false, Position=2)][string] $workingDirectory, - [parameter(Mandatory=$false, Position=3)][string] $arguments, - [parameter(Mandatory=$false, Position=4)][string] $iconLocation, - [parameter(Mandatory=$false, Position=5)][string] $description, - [parameter(Mandatory=$false, Position=6)][int] $windowStyle, - [parameter(Mandatory=$false)][switch] $runAsAdmin, - [parameter(Mandatory=$false)][switch] $pinToTaskbar, - [parameter(ValueFromRemainingArguments = $true)][Object[]]$ignoredArguments - ) - - Write-FunctionCallLogMessage -Invocation $MyInvocation -Parameters $PSBoundParameters - - # http://powershell.com/cs/blogs/tips/archive/2009/02/05/validating-a-url.aspx - function isURIWeb($address) { - $uri = $address -as [System.URI] - $uri.AbsoluteURI -ne $null -and $uri.Scheme -match '[http|https]' - } - - if (!$shortcutFilePath) { - # shortcut file path could be null if someone is trying to get special - # paths for LocalSystem (SYSTEM). - Write-Warning "Unable to create shortcut. `$shortcutFilePath can not be null." - return - } - - $shortcutDirectory = $([System.IO.Path]::GetDirectoryName($shortcutFilePath)) - if (!(Test-Path($shortcutDirectory))) { - [System.IO.Directory]::CreateDirectory($shortcutDirectory) | Out-Null - } - - if (!$targetPath) { - throw "Install-ChocolateyShortcut - `$targetPath can not be null." - } - - if(!(Test-Path($targetPath)) -and !(IsURIWeb($targetPath))) { - Write-Warning "'$targetPath' does not exist. If it is not created the shortcut will not be valid." - } - - if($iconLocation) { - if(!(Test-Path($iconLocation))) { - Write-Warning "'$iconLocation' does not exist. A default icon will be used." - } - } - - if ($workingDirectory) { - if ($workingDirectory -notmatch '%\w+%' -and !(Test-Path($workingDirectory))) { - [System.IO.Directory]::CreateDirectory($workingDirectory) | Out-Null + param( + [parameter(Mandatory = $true, Position = 0)][string] $shortcutFilePath, + [parameter(Mandatory = $true, Position = 1)][string] $targetPath, + [parameter(Mandatory = $false, Position = 2)][string] $workingDirectory, + [parameter(Mandatory = $false, Position = 3)][string] $arguments, + [parameter(Mandatory = $false, Position = 4)][string] $iconLocation, + [parameter(Mandatory = $false, Position = 5)][string] $description, + [parameter(Mandatory = $false, Position = 6)][int] $windowStyle, + [parameter(Mandatory = $false)][switch] $runAsAdmin, + [parameter(Mandatory = $false)][switch] $pinToTaskbar, + [parameter(ValueFromRemainingArguments = $true)][Object[]]$ignoredArguments + ) + + Write-FunctionCallLogMessage -Invocation $MyInvocation -Parameters $PSBoundParameters + + # http://powershell.com/cs/blogs/tips/archive/2009/02/05/validating-a-url.aspx + function isURIWeb($address) { + $uri = $address -as [System.URI] + $uri.AbsoluteURI -ne $null -and $uri.Scheme -match '[http|https]' } - } - - Write-Debug "Creating Shortcut..." - try { - $global:WshShell = New-Object -com "WScript.Shell" - $lnk = $global:WshShell.CreateShortcut($shortcutFilePath) - $lnk.TargetPath = $targetPath - $lnk.WorkingDirectory = $workingDirectory - $lnk.Arguments = $arguments - if($iconLocation) { - $lnk.IconLocation = $iconLocation - } - if ($description) { - $lnk.Description = $description - } - - if ($windowStyle) { - $lnk.WindowStyle = $windowStyle + + if (!$shortcutFilePath) { + # shortcut file path could be null if someone is trying to get special + # paths for LocalSystem (SYSTEM). + Write-Warning "Unable to create shortcut. `$shortcutFilePath can not be null." + return + } + + $shortcutDirectory = $([System.IO.Path]::GetDirectoryName($shortcutFilePath)) + if (!(Test-Path($shortcutDirectory))) { + [System.IO.Directory]::CreateDirectory($shortcutDirectory) | Out-Null + } + + if (!$targetPath) { + throw "Install-ChocolateyShortcut - `$targetPath can not be null." + } + + if (!(Test-Path($targetPath)) -and !(IsURIWeb($targetPath))) { + Write-Warning "'$targetPath' does not exist. If it is not created the shortcut will not be valid." + } + + if ($iconLocation) { + if (!(Test-Path($iconLocation))) { + Write-Warning "'$iconLocation' does not exist. A default icon will be used." + } } - $lnk.Save() - - Write-Debug "Shortcut created." - - [System.IO.FileInfo]$Path = $shortcutFilePath - If ($runAsAdmin) { - #In order to enable the "Run as Admin" checkbox, this code reads the .LNK as a stream - # and flips a specific bit while writing a new copy. It then replaces the original - # .LNK with the copy, similar to this example: http://poshcode.org/2513 - $TempFileName = [IO.Path]::GetRandomFileName() - $TempFile = [IO.FileInfo][IO.Path]::Combine($Path.Directory, $TempFileName) - $Writer = New-Object System.IO.FileStream $TempFile, ([System.IO.FileMode]::Create) - $Reader = $Path.OpenRead() - While ($Reader.Position -lt $Reader.Length) { - $Byte = $Reader.ReadByte() - If ($Reader.Position -eq 22) {$Byte = 34} - $Writer.WriteByte($Byte) + if ($workingDirectory) { + if ($workingDirectory -notmatch '%\w+%' -and !(Test-Path($workingDirectory))) { + [System.IO.Directory]::CreateDirectory($workingDirectory) | Out-Null } - $Reader.Close() - $Writer.Close() - $Path.Delete() - Rename-Item -Path $TempFile -NewName $Path.Name | Out-Null } - If ($pinToTaskbar) { - $scfilename = $Path.FullName - $pinverb = (new-object -com "shell.application").namespace($(split-path -parent $Path.FullName)).Parsename($(split-path -leaf $Path.FullName)).verbs() | - Where-Object{$_.Name -eq 'Pin to Tas&kbar'} - If ($pinverb) { $pinverb.doit() } + Write-Debug "Creating Shortcut..." + try { + $global:WshShell = New-Object -com "WScript.Shell" + $lnk = $global:WshShell.CreateShortcut($shortcutFilePath) + $lnk.TargetPath = $targetPath + $lnk.WorkingDirectory = $workingDirectory + $lnk.Arguments = $arguments + if ($iconLocation) { + $lnk.IconLocation = $iconLocation + } + if ($description) { + $lnk.Description = $description + } + + if ($windowStyle) { + $lnk.WindowStyle = $windowStyle + } + + $lnk.Save() + + Write-Debug "Shortcut created." + + [System.IO.FileInfo]$Path = $shortcutFilePath + If ($runAsAdmin) { + #In order to enable the "Run as Admin" checkbox, this code reads the .LNK as a stream + # and flips a specific bit while writing a new copy. It then replaces the original + # .LNK with the copy, similar to this example: http://poshcode.org/2513 + $TempFileName = [IO.Path]::GetRandomFileName() + $TempFile = [IO.FileInfo][IO.Path]::Combine($Path.Directory, $TempFileName) + $Writer = New-Object System.IO.FileStream $TempFile, ([System.IO.FileMode]::Create) + $Reader = $Path.OpenRead() + While ($Reader.Position -lt $Reader.Length) { + $Byte = $Reader.ReadByte() + If ($Reader.Position -eq 22) { + $Byte = 34 + } + $Writer.WriteByte($Byte) + } + $Reader.Close() + $Writer.Close() + $Path.Delete() + Rename-Item -Path $TempFile -NewName $Path.Name | Out-Null + } + + If ($pinToTaskbar) { + $scfilename = $Path.FullName + $pinverb = (New-Object -com "shell.application").namespace($(Split-Path -Parent $Path.FullName)).Parsename($(Split-Path -Leaf $Path.FullName)).verbs() | + Where-Object { $_.Name -eq 'Pin to Tas&kbar' } + If ($pinverb) { + $pinverb.doit() + } + } + } + catch { + Write-Warning "Unable to create shortcut. Error captured was $($_.Exception.Message)." } - } - catch { - Write-Warning "Unable to create shortcut. Error captured was $($_.Exception.Message)." - } } diff --git a/src/chocolatey.resources/helpers/functions/Install-ChocolateyVsixPackage.ps1 b/src/chocolatey.resources/helpers/functions/Install-ChocolateyVsixPackage.ps1 index e86a4bfadc..2cec0b99c8 100644 --- a/src/chocolatey.resources/helpers/functions/Install-ChocolateyVsixPackage.ps1 +++ b/src/chocolatey.resources/helpers/functions/Install-ChocolateyVsixPackage.ps1 @@ -15,7 +15,7 @@ # limitations under the License. function Install-ChocolateyVsixPackage { -<# + <# .SYNOPSIS Downloads and installs a VSIX package for Visual Studio @@ -136,16 +136,16 @@ Install-ChocolateyInstallPackage .LINK Install-ChocolateyZipPackage #> -param( - [alias("name")][parameter(Mandatory=$true, Position=0)][string] $packageName, - [alias("url")][parameter(Mandatory=$false, Position=1)][string] $vsixUrl, - [alias("visualStudioVersion")][parameter(Mandatory=$false, Position=2)][int] $vsVersion = 0, - [parameter(Mandatory=$false)][string] $checksum = '', - [parameter(Mandatory=$false)][string] $checksumType = '', - [parameter(Mandatory=$false)][hashtable] $options = @{Headers=@{}}, - [alias("fileFullPath")][parameter(Mandatory=$false)][string] $file = '', - [parameter(ValueFromRemainingArguments = $true)][Object[]] $ignoredArguments -) + param( + [alias("name")][parameter(Mandatory = $true, Position = 0)][string] $packageName, + [alias("url")][parameter(Mandatory = $false, Position = 1)][string] $vsixUrl, + [alias("visualStudioVersion")][parameter(Mandatory = $false, Position = 2)][int] $vsVersion = 0, + [parameter(Mandatory = $false)][string] $checksum = '', + [parameter(Mandatory = $false)][string] $checksumType = '', + [parameter(Mandatory = $false)][hashtable] $options = @{Headers = @{} }, + [alias("fileFullPath")][parameter(Mandatory = $false)][string] $file = '', + [parameter(ValueFromRemainingArguments = $true)][Object[]] $ignoredArguments + ) Write-FunctionCallLogMessage -Invocation $MyInvocation -Parameters $PSBoundParameters @@ -153,49 +153,46 @@ param( $vsixUrl = $file } - if($vsVersion -eq 0) { - if ([System.IntPtr]::Size -eq 4) - { + if ($vsVersion -eq 0) { + if ([System.IntPtr]::Size -eq 4) { <# 32bits system case #> $versions = Get-ChildItem HKLM:SOFTWARE\Microsoft\VisualStudio -ErrorAction SilentlyContinue | - Where-Object { ($_.PSChildName -match "^[0-9\.]+$") } | - Where-Object { $_.property -contains "InstallDir" } | - Sort-Object { [int]($_.PSChildName) } -descending + Where-Object { ($_.PSChildName -match "^[0-9\.]+$") } | + Where-Object { $_.property -contains "InstallDir" } | + Sort-Object { [int]($_.PSChildName) } -Descending } - else - { - $versions=(get-ChildItem HKLM:SOFTWARE\Wow6432Node\Microsoft\VisualStudio -ErrorAction SilentlyContinue | Where-Object { ($_.PSChildName -match "^[0-9\.]+$") } | Where-Object {$_.property -contains "InstallDir"} | Sort-Object {[int]($_.PSChildName)} -descending) + else { + $versions = (Get-ChildItem HKLM:SOFTWARE\Wow6432Node\Microsoft\VisualStudio -ErrorAction SilentlyContinue | Where-Object { ($_.PSChildName -match "^[0-9\.]+$") } | Where-Object { $_.property -contains "InstallDir" } | Sort-Object { [int]($_.PSChildName) } -Descending) } - if($versions -and $versions.Length){ + if ($versions -and $versions.Length) { $version = $versions[0] - }elseif($versions){ + } + elseif ($versions) { $version = $versions } } else { - if ([System.IntPtr]::Size -eq 4) - { + if ([System.IntPtr]::Size -eq 4) { <# 32bits system case #> - $versions=(get-ChildItem HKLM:SOFTWARE\Microsoft\VisualStudio -ErrorAction SilentlyContinue | Where-Object { ($_.PSChildName.EndsWith("$vsVersion.0")) } | Where-Object {$_.property -contains "InstallDir"}) + $versions = (Get-ChildItem HKLM:SOFTWARE\Microsoft\VisualStudio -ErrorAction SilentlyContinue | Where-Object { ($_.PSChildName.EndsWith("$vsVersion.0")) } | Where-Object { $_.property -contains "InstallDir" }) } - else - { - $version=(get-ChildItem HKLM:SOFTWARE\Wow6432Node\Microsoft\VisualStudio -ErrorAction SilentlyContinue | Where-Object { ($_.PSChildName.EndsWith("$vsVersion.0")) } | Where-Object {$_.property -contains "InstallDir"}) + else { + $version = (Get-ChildItem HKLM:SOFTWARE\Wow6432Node\Microsoft\VisualStudio -ErrorAction SilentlyContinue | Where-Object { ($_.PSChildName.EndsWith("$vsVersion.0")) } | Where-Object { $_.property -contains "InstallDir" }) } } if ($version) { - $vnum=$version.PSPath.Substring($version.PSPath.LastIndexOf('\')+1) - if($vnum -as [int] -lt 10) { + $vnum = $version.PSPath.Substring($version.PSPath.LastIndexOf('\') + 1) + if ($vnum -as [int] -lt 10) { throw "This installed VS version, $vnum, does not support installing VSIX packages. Version 10 is the minimum acceptable version." } - $dir=(get-itemProperty $version.PSPath "InstallDir").InstallDir + $dir = (Get-ItemProperty $version.PSPath "InstallDir").InstallDir $installer = Join-Path $dir "VsixInstaller.exe" } if ($installer) { - $download="$env:TEMP\$($packageName.Replace(' ','')).vsix" - try{ + $download = "$env:TEMP\$($packageName.Replace(' ','')).vsix" + try { Get-ChocolateyWebFile $packageName $download $vsixUrl -checksum $checksum -checksumType $checksumType -Options $options } catch { @@ -204,8 +201,9 @@ param( Write-Debug "Installing VSIX using $installer" $exitCode = Install-Vsix "$installer" "$download" - if($exitCode -gt 0 -and $exitCode -ne 1001) { #1001: Already installed - throw "There was an error installing '$packageName'. The exit code returned was $exitCode." + if ($exitCode -gt 0 -and $exitCode -ne 1001) { + #1001: Already installed + throw "There was an error installing '$packageName'. The exit code returned was $exitCode." } } else { diff --git a/src/chocolatey.resources/helpers/functions/Install-ChocolateyZipPackage.ps1 b/src/chocolatey.resources/helpers/functions/Install-ChocolateyZipPackage.ps1 index e021144a69..e49837b4e7 100644 --- a/src/chocolatey.resources/helpers/functions/Install-ChocolateyZipPackage.ps1 +++ b/src/chocolatey.resources/helpers/functions/Install-ChocolateyZipPackage.ps1 @@ -15,7 +15,7 @@ # limitations under the License. function Install-ChocolateyZipPackage { -<# + <# .SYNOPSIS Downloads file from a url and unzips it on your machine. Use Get-ChocolateyUnzip when local or embedded file. @@ -153,7 +153,7 @@ and not with the community package repository until January 2018. .PARAMETER DisableLogging OPTIONAL - This disables logging of the extracted items. It speeds up -extraction of archives with many files. +extraction of archives with many files. Usage of this parameter will prevent Uninstall-ChocolateyZipPackage from working, extracted files will have to be cleaned up with @@ -184,43 +184,47 @@ Get-ChocolateyWebFile .LINK Get-ChocolateyUnzip #> -param( - [parameter(Mandatory=$true, Position=0)][string] $packageName, - [parameter(Mandatory=$false, Position=1)][string] $url = '', - [parameter(Mandatory=$true, Position=2)] - [alias("destination")][string] $unzipLocation, - [parameter(Mandatory=$false, Position=3)] - [alias("url64")][string] $url64bit = '', - [parameter(Mandatory=$false)][string] $specificFolder ='', - [parameter(Mandatory=$false)][string] $checksum = '', - [parameter(Mandatory=$false)][string] $checksumType = '', - [parameter(Mandatory=$false)][string] $checksum64 = '', - [parameter(Mandatory=$false)][string] $checksumType64 = '', - [parameter(Mandatory=$false)][hashtable] $options = @{Headers=@{}}, - [alias("fileFullPath")][parameter(Mandatory=$false)][string] $file = '', - [alias("fileFullPath64")][parameter(Mandatory=$false)][string] $file64 = '', - [parameter(Mandatory=$false)][switch] $disableLogging, - [parameter(ValueFromRemainingArguments = $true)][Object[]] $ignoredArguments -) - - Write-FunctionCallLogMessage -Invocation $MyInvocation -Parameters $PSBoundParameters - - $fileType = 'zip' - - $chocoTempDir = $env:TEMP - $tempDir = Join-Path $chocoTempDir "$($env:chocolateyPackageName)" - if ($env:chocolateyPackageVersion -ne $null) { $tempDir = Join-Path $tempDir "$($env:chocolateyPackageVersion)"; } - $tempDir = $tempDir -replace '\\chocolatey\\chocolatey\\', '\chocolatey\' - if (![System.IO.Directory]::Exists($tempDir)) { [System.IO.Directory]::CreateDirectory($tempDir) | Out-Null } - $downloadFilePath = Join-Path $tempDir "$($packageName)Install.$fileType" - - if ($url -eq '' -or $url -eq $null) { - $url = $file - } - if ($url64bit -eq '' -or $url64bit -eq $null) { - $url64bit = $file64 - } - - $filePath = Get-ChocolateyWebFile $packageName $downloadFilePath $url $url64bit -checkSum $checkSum -checksumType $checksumType -checkSum64 $checkSum64 -checksumType64 $checksumType64 -options $options -getOriginalFileName - Get-ChocolateyUnzip "$filePath" $unzipLocation $specificFolder $packageName -disableLogging:$disableLogging + param( + [parameter(Mandatory = $true, Position = 0)][string] $packageName, + [parameter(Mandatory = $false, Position = 1)][string] $url = '', + [parameter(Mandatory = $true, Position = 2)] + [alias("destination")][string] $unzipLocation, + [parameter(Mandatory = $false, Position = 3)] + [alias("url64")][string] $url64bit = '', + [parameter(Mandatory = $false)][string] $specificFolder = '', + [parameter(Mandatory = $false)][string] $checksum = '', + [parameter(Mandatory = $false)][string] $checksumType = '', + [parameter(Mandatory = $false)][string] $checksum64 = '', + [parameter(Mandatory = $false)][string] $checksumType64 = '', + [parameter(Mandatory = $false)][hashtable] $options = @{Headers = @{} }, + [alias("fileFullPath")][parameter(Mandatory = $false)][string] $file = '', + [alias("fileFullPath64")][parameter(Mandatory = $false)][string] $file64 = '', + [parameter(Mandatory = $false)][switch] $disableLogging, + [parameter(ValueFromRemainingArguments = $true)][Object[]] $ignoredArguments + ) + + Write-FunctionCallLogMessage -Invocation $MyInvocation -Parameters $PSBoundParameters + + $fileType = 'zip' + + $chocoTempDir = $env:TEMP + $tempDir = Join-Path $chocoTempDir "$($env:chocolateyPackageName)" + if ($env:chocolateyPackageVersion -ne $null) { + $tempDir = Join-Path $tempDir "$($env:chocolateyPackageVersion)"; + } + $tempDir = $tempDir -replace '\\chocolatey\\chocolatey\\', '\chocolatey\' + if (![System.IO.Directory]::Exists($tempDir)) { + [System.IO.Directory]::CreateDirectory($tempDir) | Out-Null + } + $downloadFilePath = Join-Path $tempDir "$($packageName)Install.$fileType" + + if ($url -eq '' -or $url -eq $null) { + $url = $file + } + if ($url64bit -eq '' -or $url64bit -eq $null) { + $url64bit = $file64 + } + + $filePath = Get-ChocolateyWebFile $packageName $downloadFilePath $url $url64bit -checkSum $checkSum -checksumType $checksumType -checkSum64 $checkSum64 -checksumType64 $checksumType64 -options $options -getOriginalFileName + Get-ChocolateyUnzip "$filePath" $unzipLocation $specificFolder $packageName -disableLogging:$disableLogging } diff --git a/src/chocolatey.resources/helpers/functions/Install-Vsix.ps1 b/src/chocolatey.resources/helpers/functions/Install-Vsix.ps1 index 0386c266cd..be95e360d6 100644 --- a/src/chocolatey.resources/helpers/functions/Install-Vsix.ps1 +++ b/src/chocolatey.resources/helpers/functions/Install-Vsix.ps1 @@ -15,7 +15,7 @@ # limitations under the License. function Install-Vsix { -<# + <# .SYNOPSIS DO NOT USE. Not part of the public API. @@ -44,24 +44,24 @@ Allows splatting with arguments that do not apply. Do not use directly. .LINK Install-ChocolateyVsixPackage #> -param ( - [parameter(Mandatory=$true, Position=0)][string] $installer, - [parameter(Mandatory=$true, Position=1)][string] $installFile, - [parameter(ValueFromRemainingArguments = $true)][Object[]] $ignoredArguments -) + param ( + [parameter(Mandatory = $true, Position = 0)][string] $installer, + [parameter(Mandatory = $true, Position = 1)][string] $installFile, + [parameter(ValueFromRemainingArguments = $true)][Object[]] $ignoredArguments + ) - Write-FunctionCallLogMessage -Invocation $MyInvocation -Parameters $PSBoundParameters + Write-FunctionCallLogMessage -Invocation $MyInvocation -Parameters $PSBoundParameters - if ($env:chocolateyPackageName -ne $null -and $env:chocolateyPackageName -eq $env:ChocolateyInstallDirectoryPackage) { - Write-Warning "Install Directory override not available for VSIX packages." - } + if ($env:chocolateyPackageName -ne $null -and $env:chocolateyPackageName -eq $env:ChocolateyInstallDirectoryPackage) { + Write-Warning "Install Directory override not available for VSIX packages." + } - Write-Host "Installing $installFile using $installer" - $psi = New-Object System.Diagnostics.ProcessStartInfo - $psi.FileName=$installer - $psi.Arguments="/q $installFile" - $s = [System.Diagnostics.Process]::Start($psi) - $s.WaitForExit() + Write-Host "Installing $installFile using $installer" + $psi = New-Object System.Diagnostics.ProcessStartInfo + $psi.FileName = $installer + $psi.Arguments = "/q $installFile" + $s = [System.Diagnostics.Process]::Start($psi) + $s.WaitForExit() - return $s.ExitCode + return $s.ExitCode } diff --git a/src/chocolatey.resources/helpers/functions/Set-EnvironmentVariable.ps1 b/src/chocolatey.resources/helpers/functions/Set-EnvironmentVariable.ps1 index 949320d866..64e465e758 100644 --- a/src/chocolatey.resources/helpers/functions/Set-EnvironmentVariable.ps1 +++ b/src/chocolatey.resources/helpers/functions/Set-EnvironmentVariable.ps1 @@ -15,7 +15,7 @@ # limitations under the License. function Set-EnvironmentVariable { -<# + <# .SYNOPSIS **NOTE:** Administrative Access Required when `-Scope 'Machine'.` @@ -55,73 +55,74 @@ Install-ChocolateyPath .LINK Get-EnvironmentVariable #> -param ( - [parameter(Mandatory=$true, Position=0)][string] $Name, - [parameter(Mandatory=$false, Position=1)][string] $Value, - [parameter(Mandatory=$false, Position=2)] - [System.EnvironmentVariableTarget] $Scope, - [parameter(ValueFromRemainingArguments = $true)][Object[]] $ignoredArguments -) - - Write-FunctionCallLogMessage -Invocation $MyInvocation -Parameters $PSBoundParameters - - if ($Scope -eq [System.EnvironmentVariableTarget]::Process -or $Value -eq $null -or $Value -eq '') { - return [Environment]::SetEnvironmentVariable($Name, $Value, $Scope) - } - - [string]$keyHive = 'HKEY_LOCAL_MACHINE' - [string]$registryKey = "SYSTEM\CurrentControlSet\Control\Session Manager\Environment\" - [Microsoft.Win32.RegistryKey] $win32RegistryKey = [Microsoft.Win32.Registry]::LocalMachine.OpenSubKey($registryKey) - if ($Scope -eq [System.EnvironmentVariableTarget]::User) { - $keyHive = 'HKEY_CURRENT_USER' - $registryKey = "Environment" - [Microsoft.Win32.RegistryKey] $win32RegistryKey = [Microsoft.Win32.Registry]::CurrentUser.OpenSubKey($registryKey) - } - - [Microsoft.Win32.RegistryValueKind]$registryType = [Microsoft.Win32.RegistryValueKind]::String - try { - if ($win32RegistryKey.GetValueNames() -contains $Name) - { - $registryType = $win32RegistryKey.GetValueKind($Name) + param ( + [parameter(Mandatory = $true, Position = 0)][string] $Name, + [parameter(Mandatory = $false, Position = 1)][string] $Value, + [parameter(Mandatory = $false, Position = 2)] + [System.EnvironmentVariableTarget] $Scope, + [parameter(ValueFromRemainingArguments = $true)][Object[]] $ignoredArguments + ) + + Write-FunctionCallLogMessage -Invocation $MyInvocation -Parameters $PSBoundParameters + + if ($Scope -eq [System.EnvironmentVariableTarget]::Process -or $Value -eq $null -or $Value -eq '') { + return [Environment]::SetEnvironmentVariable($Name, $Value, $Scope) } - } catch { - # the value doesn't yet exist - # move along, nothing to see here - } - Write-Debug "Registry type for $Name is/will be $registryType" - - if ($Name -eq 'PATH') { - $registryType = [Microsoft.Win32.RegistryValueKind]::ExpandString - } - - [Microsoft.Win32.Registry]::SetValue($keyHive + "\" + $registryKey, $Name, $Value, $registryType) - - try { - # make everything refresh - # because sometimes explorer.exe just doesn't get the message that things were updated. - if (-not ("win32.nativemethods" -as [type])) { - # import sendmessagetimeout from win32 - add-type -Namespace Win32 -Name NativeMethods -MemberDefinition @" + + [string]$keyHive = 'HKEY_LOCAL_MACHINE' + [string]$registryKey = "SYSTEM\CurrentControlSet\Control\Session Manager\Environment\" + [Microsoft.Win32.RegistryKey] $win32RegistryKey = [Microsoft.Win32.Registry]::LocalMachine.OpenSubKey($registryKey) + if ($Scope -eq [System.EnvironmentVariableTarget]::User) { + $keyHive = 'HKEY_CURRENT_USER' + $registryKey = "Environment" + [Microsoft.Win32.RegistryKey] $win32RegistryKey = [Microsoft.Win32.Registry]::CurrentUser.OpenSubKey($registryKey) + } + + [Microsoft.Win32.RegistryValueKind]$registryType = [Microsoft.Win32.RegistryValueKind]::String + try { + if ($win32RegistryKey.GetValueNames() -contains $Name) { + $registryType = $win32RegistryKey.GetValueKind($Name) + } + } + catch { + # the value doesn't yet exist + # move along, nothing to see here + } + Write-Debug "Registry type for $Name is/will be $registryType" + + if ($Name -eq 'PATH') { + $registryType = [Microsoft.Win32.RegistryValueKind]::ExpandString + } + + [Microsoft.Win32.Registry]::SetValue($keyHive + "\" + $registryKey, $Name, $Value, $registryType) + + try { + # make everything refresh + # because sometimes explorer.exe just doesn't get the message that things were updated. + if (-not ("win32.nativemethods" -as [type])) { + # import sendmessagetimeout from win32 + Add-Type -Namespace Win32 -Name NativeMethods -MemberDefinition @" [DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)] public static extern IntPtr SendMessageTimeout( IntPtr hWnd, uint Msg, UIntPtr wParam, string lParam, uint fuFlags, uint uTimeout, out UIntPtr lpdwResult); "@ - } + } - $HWND_BROADCAST = [intptr]0xffff; - $WM_SETTINGCHANGE = 0x1a; - $result = [uintptr]::zero + $HWND_BROADCAST = [intptr]0xffff; + $WM_SETTINGCHANGE = 0x1a; + $result = [uintptr]::zero - # notify all windows of environment block change - [win32.nativemethods]::SendMessageTimeout($HWND_BROADCAST, $WM_SETTINGCHANGE, [uintptr]::Zero, "Environment", 2, 5000, [ref]$result) | Out-Null + # notify all windows of environment block change + [win32.nativemethods]::SendMessageTimeout($HWND_BROADCAST, $WM_SETTINGCHANGE, [uintptr]::Zero, "Environment", 2, 5000, [ref]$result) | Out-Null - # Set a user environment variable making the system refresh - $setx = "$($env:SystemRoot)\System32\setx.exe" - & "$setx" ChocolateyLastPathUpdate `"$((Get-Date).ToFileTime())`" | Out-Null - } catch { - Write-Warning "Failure attempting to let Explorer know about updated environment settings.`n $($_.Exception.Message)" - } + # Set a user environment variable making the system refresh + $setx = "$($env:SystemRoot)\System32\setx.exe" + & "$setx" ChocolateyLastPathUpdate `"$((Get-Date).ToFileTime())`" | Out-Null + } + catch { + Write-Warning "Failure attempting to let Explorer know about updated environment settings.`n $($_.Exception.Message)" + } - Update-SessionEnvironment + Update-SessionEnvironment } diff --git a/src/chocolatey.resources/helpers/functions/Set-PowerShellExitCode.ps1 b/src/chocolatey.resources/helpers/functions/Set-PowerShellExitCode.ps1 index ec02f95721..99590e96ae 100644 --- a/src/chocolatey.resources/helpers/functions/Set-PowerShellExitCode.ps1 +++ b/src/chocolatey.resources/helpers/functions/Set-PowerShellExitCode.ps1 @@ -15,7 +15,7 @@ # limitations under the License. Function Set-PowerShellExitCode { -<# + <# .SYNOPSIS Sets the exit code for the PowerShell scripts. @@ -41,23 +41,24 @@ Allows splatting with arguments that do not apply. Do not use directly. .EXAMPLE Set-PowerShellExitCode 3010 #> -param ( - [parameter(Mandatory=$false, Position=0)][int] $exitCode, - [parameter(ValueFromRemainingArguments = $true)][Object[]] $ignoredArguments -) + param ( + [parameter(Mandatory = $false, Position = 0)][int] $exitCode, + [parameter(ValueFromRemainingArguments = $true)][Object[]] $ignoredArguments + ) - # Do not log function call - can mess things up + # Do not log function call - can mess things up - if ($exitCode -eq $null -or $exitCode -eq '') { - Write-Debug '$exitCode was passed null' - return - } + if ($exitCode -eq $null -or $exitCode -eq '') { + Write-Debug '$exitCode was passed null' + return + } - try { - $host.SetShouldExit($exitCode); - } catch { - Write-Warning "Unable to set host exit code" - } + try { + $host.SetShouldExit($exitCode); + } + catch { + Write-Warning "Unable to set host exit code" + } - $env:ChocolateyExitCode = $exitCode; + $env:ChocolateyExitCode = $exitCode; } diff --git a/src/chocolatey.resources/helpers/functions/Start-ChocolateyProcessAsAdmin.ps1 b/src/chocolatey.resources/helpers/functions/Start-ChocolateyProcessAsAdmin.ps1 index d59946746f..a05a69ba49 100644 --- a/src/chocolatey.resources/helpers/functions/Start-ChocolateyProcessAsAdmin.ps1 +++ b/src/chocolatey.resources/helpers/functions/Start-ChocolateyProcessAsAdmin.ps1 @@ -15,7 +15,7 @@ # limitations under the License. function Start-ChocolateyProcessAsAdmin { -<# + <# .SYNOPSIS **NOTE:** Administrative Access Required. @@ -111,57 +111,64 @@ Install-ChocolateyPackage .LINK Install-ChocolateyInstallPackage #> -param( - [parameter(Mandatory=$false, Position=0)][string[]] $statements, - [parameter(Mandatory=$false, Position=1)][string] $exeToRun = 'powershell', - [parameter(Mandatory=$false)][switch] $elevated = $true, - [parameter(Mandatory=$false)][switch] $minimized, - [parameter(Mandatory=$false)][switch] $noSleep, - [parameter(Mandatory=$false)] $validExitCodes = @(0), - [parameter(Mandatory=$false)][string] $workingDirectory = $null, - [parameter(Mandatory=$false)][string] $sensitiveStatements = '', - [parameter(ValueFromRemainingArguments = $true)][Object[]] $ignoredArguments -) - [string]$statements = $statements -join ' ' - - Write-FunctionCallLogMessage -Invocation $MyInvocation -Parameters $PSBoundParameters - - if ($workingDirectory -eq $null) { - $pwd = $(Get-Location -PSProvider 'FileSystem') - if ($pwd -eq $null -or $pwd.ProviderPath -eq $null) { - Write-Debug "Unable to use current location for Working Directory. Using Cache Location instead." - $workingDirectory = $env:TEMP + param( + [parameter(Mandatory = $false, Position = 0)][string[]] $statements, + [parameter(Mandatory = $false, Position = 1)][string] $exeToRun = 'powershell', + [parameter(Mandatory = $false)][switch] $elevated = $true, + [parameter(Mandatory = $false)][switch] $minimized, + [parameter(Mandatory = $false)][switch] $noSleep, + [parameter(Mandatory = $false)] $validExitCodes = @(0), + [parameter(Mandatory = $false)][string] $workingDirectory = $null, + [parameter(Mandatory = $false)][string] $sensitiveStatements = '', + [parameter(ValueFromRemainingArguments = $true)][Object[]] $ignoredArguments + ) + [string]$statements = $statements -join ' ' + + Write-FunctionCallLogMessage -Invocation $MyInvocation -Parameters $PSBoundParameters + + if ($workingDirectory -eq $null) { + $pwd = $(Get-Location -PSProvider 'FileSystem') + if ($pwd -eq $null -or $pwd.ProviderPath -eq $null) { + Write-Debug "Unable to use current location for Working Directory. Using Cache Location instead." + $workingDirectory = $env:TEMP + } + $workingDirectory = $pwd.ProviderPath } - $workingDirectory = $pwd.ProviderPath - } - $alreadyElevated = $false - if (Test-ProcessAdminRights) { - $alreadyElevated = $true - } - - $dbMessagePrepend = "Elevating permissions and running" - if (!$elevated) { - $dbMessagePrepend = "Running" - } - - try { - if ($exeToRun -ne $null) { $exeToRun = $exeToRun -replace "`0", "" } - if ($statements -ne $null) { $statements = $statements -replace "`0", "" } - } catch { - Write-Debug "Removing null characters resulted in an error - $($_.Exception.Message)" - } - - if ($exeToRun -ne $null) { - $exeToRun = $exeToRun.Trim().Trim("'").Trim('"') - } - - $wrappedStatements = $statements - if ($wrappedStatements -eq $null) { $wrappedStatements = ''} - - if ($exeToRun -eq 'powershell') { - $exeToRun = "$($env:SystemRoot)\System32\WindowsPowerShell\v1.0\powershell.exe" - $importChocolateyHelpers = "& import-module -name '$helpersPath\chocolateyInstaller.psm1' -Verbose:`$false | Out-Null;" - $block = @" + $alreadyElevated = $false + if (Test-ProcessAdminRights) { + $alreadyElevated = $true + } + + $dbMessagePrepend = "Elevating permissions and running" + if (!$elevated) { + $dbMessagePrepend = "Running" + } + + try { + if ($exeToRun -ne $null) { + $exeToRun = $exeToRun -replace "`0", "" + } + if ($statements -ne $null) { + $statements = $statements -replace "`0", "" + } + } + catch { + Write-Debug "Removing null characters resulted in an error - $($_.Exception.Message)" + } + + if ($exeToRun -ne $null) { + $exeToRun = $exeToRun.Trim().Trim("'").Trim('"') + } + + $wrappedStatements = $statements + if ($wrappedStatements -eq $null) { + $wrappedStatements = '' + } + + if ($exeToRun -eq 'powershell') { + $exeToRun = "$($env:SystemRoot)\System32\WindowsPowerShell\v1.0\powershell.exe" + $importChocolateyHelpers = "& import-module -name '$helpersPath\chocolateyInstaller.psm1' -Verbose:`$false | Out-Null;" + $block = @" `$noSleep = `$$noSleep #`$env:ChocolateyEnvironmentDebug='false' #`$env:ChocolateyEnvironmentVerbose='false' @@ -176,165 +183,219 @@ param( throw } "@ - $encoded = [Convert]::ToBase64String([System.Text.Encoding]::Unicode.GetBytes($block)) - $wrappedStatements = "-NoLogo -NonInteractive -NoProfile -ExecutionPolicy Bypass -InputFormat Text -OutputFormat Text -EncodedCommand $encoded" - $dbgMessage = @" + $encoded = [Convert]::ToBase64String([System.Text.Encoding]::Unicode.GetBytes($block)) + $wrappedStatements = "-NoLogo -NonInteractive -NoProfile -ExecutionPolicy Bypass -InputFormat Text -OutputFormat Text -EncodedCommand $encoded" + $dbgMessage = @" $dbMessagePrepend powershell block: $block This may take a while, depending on the statements. "@ - - } - else - { - $dbgMessage = @" + } + else { + $dbgMessage = @" $dbMessagePrepend [`"$exeToRun`" $wrappedStatements]. This may take a while, depending on the statements. "@ - } - - Write-Debug $dbgMessage - - $exeIsTextFile = [System.IO.Path]::GetFullPath($exeToRun) + ".istext" - if ([System.IO.File]::Exists($exeIsTextFile)) { - Set-PowerShellExitCode 4 - throw "The file was a text file but is attempting to be run as an executable - '$exeToRun'" - } - - if ($exeToRun -eq 'msiexec' -or $exeToRun -eq 'msiexec.exe') { - $exeToRun = "$($env:SystemRoot)\System32\msiexec.exe" - } - - if (!([System.IO.File]::Exists($exeToRun)) -and $exeToRun -notmatch 'msiexec') { - Write-Warning "May not be able to find '$exeToRun'. Please use full path for executables." - # until we have search paths enabled, let's just pass a warning - #Set-PowerShellExitCode 2 - #throw "Could not find '$exeToRun'" - } - - # Redirecting output slows things down a bit. - $writeOutput = { - if ($EventArgs.Data -ne $null) { - Write-Verbose "$($EventArgs.Data)" } - } - $writeError = { - if ($EventArgs.Data -ne $null) { - Write-Error "$($EventArgs.Data)" + Write-Debug $dbgMessage + + $exeIsTextFile = [System.IO.Path]::GetFullPath($exeToRun) + ".istext" + if ([System.IO.File]::Exists($exeIsTextFile)) { + Set-PowerShellExitCode 4 + throw "The file was a text file but is attempting to be run as an executable - '$exeToRun'" + } + + if ($exeToRun -eq 'msiexec' -or $exeToRun -eq 'msiexec.exe') { + $exeToRun = "$($env:SystemRoot)\System32\msiexec.exe" + } + + if (!([System.IO.File]::Exists($exeToRun)) -and $exeToRun -notmatch 'msiexec') { + Write-Warning "May not be able to find '$exeToRun'. Please use full path for executables." + # until we have search paths enabled, let's just pass a warning + #Set-PowerShellExitCode 2 + #throw "Could not find '$exeToRun'" + } + + # Redirecting output slows things down a bit. + $writeOutput = { + if ($EventArgs.Data -ne $null) { + Write-Verbose "$($EventArgs.Data)" + } + } + + $writeError = { + if ($EventArgs.Data -ne $null) { + Write-Error "$($EventArgs.Data)" + } + } + + $process = New-Object System.Diagnostics.Process + $process.EnableRaisingEvents = $true + Register-ObjectEvent -InputObject $process -SourceIdentifier "LogOutput_ChocolateyProc" -EventName OutputDataReceived -Action $writeOutput | Out-Null + Register-ObjectEvent -InputObject $process -SourceIdentifier "LogErrors_ChocolateyProc" -EventName ErrorDataReceived -Action $writeError | Out-Null + + #$process.StartInfo = New-Object System.Diagnostics.ProcessStartInfo($exeToRun, $wrappedStatements) + # in case empty args makes a difference, try to be compatible with the older + # version + $psi = New-Object System.Diagnostics.ProcessStartInfo + + $psi.FileName = $exeToRun + if ($wrappedStatements -ne '') { + $psi.Arguments = "$wrappedStatements" + } + if ($sensitiveStatements -ne $null -and $sensitiveStatements -ne '') { + Write-Host "Sensitive arguments have been passed. Adding to arguments." + $psi.Arguments += " $sensitiveStatements" + } + $process.StartInfo = $psi + + # process start info + $process.StartInfo.RedirectStandardOutput = $true + $process.StartInfo.RedirectStandardError = $true + $process.StartInfo.UseShellExecute = $false + $process.StartInfo.WorkingDirectory = $workingDirectory + + if ($elevated -and -not $alreadyElevated -and [Environment]::OSVersion.Version -ge (New-Object 'Version' 6, 0)) { + # this doesn't actually currently work - because we are not running under shell execute + Write-Debug "Setting RunAs for elevation" + $process.StartInfo.Verb = "RunAs" + } + if ($minimized) { + $process.StartInfo.WindowStyle = [System.Diagnostics.ProcessWindowStyle]::Minimized + } + + $process.Start() | Out-Null + if ($process.StartInfo.RedirectStandardOutput) { + $process.BeginOutputReadLine() + } + if ($process.StartInfo.RedirectStandardError) { + $process.BeginErrorReadLine() + } + $process.WaitForExit() + + # For some reason this forces the jobs to finish and waits for + # them to do so. Without this it never finishes. + Unregister-Event -SourceIdentifier "LogOutput_ChocolateyProc" + Unregister-Event -SourceIdentifier "LogErrors_ChocolateyProc" + + # sometimes the process hasn't fully exited yet. + for ($loopCount = 1; $loopCount -le 15; $loopCount++) { + if ($process.HasExited) { + break; + } + Write-Debug "Waiting for process to exit - $loopCount/15 seconds"; + Start-Sleep 1; + } + + $exitCode = $process.ExitCode + $process.Dispose() + + Write-Debug "Command [`"$exeToRun`" $wrappedStatements] exited with `'$exitCode`'." + + $exitErrorMessage = '' + $errorMessageAddendum = " This is most likely an issue with the '$env:chocolateyPackageName' package and not with Chocolatey itself. Please follow up with the package maintainer(s) directly." + + switch ($exitCode) { + 0 { + break + } + 1 { + break + } + 3010 { + break + } + # NSIS - http://nsis.sourceforge.net/Docs/AppendixD.html + # InnoSetup - http://www.jrsoftware.org/ishelp/index.php?topic=setupexitcodes + 2 { + $exitErrorMessage = 'Setup was cancelled.'; break + } + 3 { + $exitErrorMessage = 'A fatal error occurred when preparing or moving to next install phase. Check to be sure you have enough memory to perform an installation and try again.'; break + } + 4 { + $exitErrorMessage = 'A fatal error occurred during installation process.' + $errorMessageAddendum; break + } + 5 { + $exitErrorMessage = 'User (you) cancelled the installation.'; break + } + 6 { + $exitErrorMessage = 'Setup process was forcefully terminated by the debugger.'; break + } + 7 { + $exitErrorMessage = 'While preparing to install, it was determined setup cannot proceed with the installation. Please be sure the software can be installed on your system.'; break + } + 8 { + $exitErrorMessage = 'While preparing to install, it was determined setup cannot proceed with the installation until you restart the system. Please reboot and try again.'; break + } + # MSI - https://msdn.microsoft.com/en-us/library/windows/desktop/aa376931.aspx + 1602 { + $exitErrorMessage = 'User (you) cancelled the installation.'; break + } + 1603 { + $exitErrorMessage = "Generic MSI Error. This is a local environment error, not an issue with a package or the MSI itself - it could mean a pending reboot is necessary prior to install or something else (like the same version is already installed). Please see MSI log if available. If not, try again adding `'--install-arguments=`"`'/l*v c:\$($env:chocolateyPackageName)_msi_install.log`'`"`'. Then search the MSI Log for `"Return Value 3`" and look above that for the error."; break + } + 1618 { + $exitErrorMessage = 'Another installation currently in progress. Try again later.'; break + } + 1619 { + $exitErrorMessage = 'MSI could not be found - it is possibly corrupt or not an MSI at all. If it was downloaded and the MSI is less than 30K, try opening it in an editor like Notepad++ as it is likely HTML.' + $errorMessageAddendum; break + } + 1620 { + $exitErrorMessage = 'MSI could not be opened - it is possibly corrupt or not an MSI at all. If it was downloaded and the MSI is less than 30K, try opening it in an editor like Notepad++ as it is likely HTML.' + $errorMessageAddendum; break + } + 1622 { + $exitErrorMessage = 'Something is wrong with the install log location specified. Please fix this in the package silent arguments (or in install arguments you specified). The directory specified as part of the log file path must exist for an MSI to be able to log to that directory.' + $errorMessageAddendum; break + } + 1623 { + $exitErrorMessage = 'This MSI has a language that is not supported by your system. Contact package maintainer(s) if there is an install available in your language and you would like it added to the packaging.'; break + } + 1625 { + $exitErrorMessage = 'Installation of this MSI is forbidden by system policy. Please contact your system administrators.'; break + } + 1632 { + $exitErrorMessage = 'Installation of this MSI is not supported on this platform. Contact package maintainer(s) if you feel this is in error or if you need an architecture that is not available with the current packaging.'; break + } + 1633 { + $exitErrorMessage = 'Installation of this MSI is not supported on this platform. Contact package maintainer(s) if you feel this is in error or if you need an architecture that is not available with the current packaging.'; break + } + 1638 { + $exitErrorMessage = 'This MSI requires uninstall prior to installing a different version. Please ask the package maintainer(s) to add a check in the chocolateyInstall.ps1 script and uninstall if the software is installed.' + $errorMessageAddendum; break + } + 1639 { + $exitErrorMessage = 'The command line arguments passed to the MSI are incorrect. If you passed in additional arguments, please adjust. Otherwise followup with the package maintainer(s) to get this fixed.' + $errorMessageAddendum; break + } + 1640 { + $exitErrorMessage = 'Cannot install MSI when running from remote desktop (terminal services). This should automatically be handled in licensed editions. For open source editions, you may need to run change.exe prior to running Chocolatey or not use terminal services.'; break + } + 1645 { + $exitErrorMessage = 'Cannot install MSI when running from remote desktop (terminal services). This should automatically be handled in licensed editions. For open source editions, you may need to run change.exe prior to running Chocolatey or not use terminal services.'; break + } + } + + if ($exitErrorMessage) { + $errorMessageSpecific = "Exit code indicates the following: $exitErrorMessage." + Write-Warning $exitErrorMessage + } + else { + $errorMessageSpecific = 'See log for possible error messages.' + } + + if ($validExitCodes -notcontains $exitCode) { + Set-PowerShellExitCode $exitCode + throw "Running [`"$exeToRun`" $wrappedStatements] was not successful. Exit code was '$exitCode'. $($errorMessageSpecific)" } - } - - $process = New-Object System.Diagnostics.Process - $process.EnableRaisingEvents = $true - Register-ObjectEvent -InputObject $process -SourceIdentifier "LogOutput_ChocolateyProc" -EventName OutputDataReceived -Action $writeOutput | Out-Null - Register-ObjectEvent -InputObject $process -SourceIdentifier "LogErrors_ChocolateyProc" -EventName ErrorDataReceived -Action $writeError | Out-Null - - #$process.StartInfo = New-Object System.Diagnostics.ProcessStartInfo($exeToRun, $wrappedStatements) - # in case empty args makes a difference, try to be compatible with the older - # version - $psi = New-Object System.Diagnostics.ProcessStartInfo - - $psi.FileName = $exeToRun - if ($wrappedStatements -ne '') { - $psi.Arguments = "$wrappedStatements" - } - if ($sensitiveStatements -ne $null -and $sensitiveStatements -ne '') { - Write-Host "Sensitive arguments have been passed. Adding to arguments." - $psi.Arguments += " $sensitiveStatements" - } - $process.StartInfo = $psi - - # process start info - $process.StartInfo.RedirectStandardOutput = $true - $process.StartInfo.RedirectStandardError = $true - $process.StartInfo.UseShellExecute = $false - $process.StartInfo.WorkingDirectory = $workingDirectory - - if ($elevated -and -not $alreadyElevated -and [Environment]::OSVersion.Version -ge (New-Object 'Version' 6,0)){ - # this doesn't actually currently work - because we are not running under shell execute - Write-Debug "Setting RunAs for elevation" - $process.StartInfo.Verb = "RunAs" - } - if ($minimized) { - $process.StartInfo.WindowStyle = [System.Diagnostics.ProcessWindowStyle]::Minimized - } - - $process.Start() | Out-Null - if ($process.StartInfo.RedirectStandardOutput) { $process.BeginOutputReadLine() } - if ($process.StartInfo.RedirectStandardError) { $process.BeginErrorReadLine() } - $process.WaitForExit() - - # For some reason this forces the jobs to finish and waits for - # them to do so. Without this it never finishes. - Unregister-Event -SourceIdentifier "LogOutput_ChocolateyProc" - Unregister-Event -SourceIdentifier "LogErrors_ChocolateyProc" - - # sometimes the process hasn't fully exited yet. - for ($loopCount=1; $loopCount -le 15; $loopCount++) { - if ($process.HasExited) { break; } - Write-Debug "Waiting for process to exit - $loopCount/15 seconds"; - Start-Sleep 1; - } - - $exitCode = $process.ExitCode - $process.Dispose() - - Write-Debug "Command [`"$exeToRun`" $wrappedStatements] exited with `'$exitCode`'." - - $exitErrorMessage = '' - $errorMessageAddendum = " This is most likely an issue with the '$env:chocolateyPackageName' package and not with Chocolatey itself. Please follow up with the package maintainer(s) directly." - - switch ($exitCode) { - 0 { break } - 1 { break } - 3010 { break } - # NSIS - http://nsis.sourceforge.net/Docs/AppendixD.html - # InnoSetup - http://www.jrsoftware.org/ishelp/index.php?topic=setupexitcodes - 2 { $exitErrorMessage = 'Setup was cancelled.'; break } - 3 { $exitErrorMessage = 'A fatal error occurred when preparing or moving to next install phase. Check to be sure you have enough memory to perform an installation and try again.'; break } - 4 { $exitErrorMessage = 'A fatal error occurred during installation process.' + $errorMessageAddendum; break } - 5 { $exitErrorMessage = 'User (you) cancelled the installation.'; break } - 6 { $exitErrorMessage = 'Setup process was forcefully terminated by the debugger.'; break } - 7 { $exitErrorMessage = 'While preparing to install, it was determined setup cannot proceed with the installation. Please be sure the software can be installed on your system.'; break } - 8 { $exitErrorMessage = 'While preparing to install, it was determined setup cannot proceed with the installation until you restart the system. Please reboot and try again.'; break } - # MSI - https://msdn.microsoft.com/en-us/library/windows/desktop/aa376931.aspx - 1602 { $exitErrorMessage = 'User (you) cancelled the installation.'; break } - 1603 { $exitErrorMessage = "Generic MSI Error. This is a local environment error, not an issue with a package or the MSI itself - it could mean a pending reboot is necessary prior to install or something else (like the same version is already installed). Please see MSI log if available. If not, try again adding `'--install-arguments=`"`'/l*v c:\$($env:chocolateyPackageName)_msi_install.log`'`"`'. Then search the MSI Log for `"Return Value 3`" and look above that for the error."; break } - 1618 { $exitErrorMessage = 'Another installation currently in progress. Try again later.'; break } - 1619 { $exitErrorMessage = 'MSI could not be found - it is possibly corrupt or not an MSI at all. If it was downloaded and the MSI is less than 30K, try opening it in an editor like Notepad++ as it is likely HTML.' + $errorMessageAddendum; break } - 1620 { $exitErrorMessage = 'MSI could not be opened - it is possibly corrupt or not an MSI at all. If it was downloaded and the MSI is less than 30K, try opening it in an editor like Notepad++ as it is likely HTML.' + $errorMessageAddendum; break } - 1622 { $exitErrorMessage = 'Something is wrong with the install log location specified. Please fix this in the package silent arguments (or in install arguments you specified). The directory specified as part of the log file path must exist for an MSI to be able to log to that directory.' + $errorMessageAddendum; break } - 1623 { $exitErrorMessage = 'This MSI has a language that is not supported by your system. Contact package maintainer(s) if there is an install available in your language and you would like it added to the packaging.'; break } - 1625 { $exitErrorMessage = 'Installation of this MSI is forbidden by system policy. Please contact your system administrators.'; break } - 1632 { $exitErrorMessage = 'Installation of this MSI is not supported on this platform. Contact package maintainer(s) if you feel this is in error or if you need an architecture that is not available with the current packaging.'; break } - 1633 { $exitErrorMessage = 'Installation of this MSI is not supported on this platform. Contact package maintainer(s) if you feel this is in error or if you need an architecture that is not available with the current packaging.'; break } - 1638 { $exitErrorMessage = 'This MSI requires uninstall prior to installing a different version. Please ask the package maintainer(s) to add a check in the chocolateyInstall.ps1 script and uninstall if the software is installed.' + $errorMessageAddendum; break } - 1639 { $exitErrorMessage = 'The command line arguments passed to the MSI are incorrect. If you passed in additional arguments, please adjust. Otherwise followup with the package maintainer(s) to get this fixed.' + $errorMessageAddendum; break } - 1640 { $exitErrorMessage = 'Cannot install MSI when running from remote desktop (terminal services). This should automatically be handled in licensed editions. For open source editions, you may need to run change.exe prior to running Chocolatey or not use terminal services.'; break } - 1645 { $exitErrorMessage = 'Cannot install MSI when running from remote desktop (terminal services). This should automatically be handled in licensed editions. For open source editions, you may need to run change.exe prior to running Chocolatey or not use terminal services.'; break } - } - - if ($exitErrorMessage) { - $errorMessageSpecific = "Exit code indicates the following: $exitErrorMessage." - Write-Warning $exitErrorMessage - } else { - $errorMessageSpecific = 'See log for possible error messages.' - } - - if ($validExitCodes -notcontains $exitCode) { - Set-PowerShellExitCode $exitCode - throw "Running [`"$exeToRun`" $wrappedStatements] was not successful. Exit code was '$exitCode'. $($errorMessageSpecific)" - } else { - $chocoSuccessCodes = @(0, 1605, 1614, 1641, 3010) - if ($chocoSuccessCodes -notcontains $exitCode) { - Write-Warning "Exit code '$exitCode' was considered valid by script, but not as a Chocolatey success code. Returning '0'." - $exitCode = 0 + else { + $chocoSuccessCodes = @(0, 1605, 1614, 1641, 3010) + if ($chocoSuccessCodes -notcontains $exitCode) { + Write-Warning "Exit code '$exitCode' was considered valid by script, but not as a Chocolatey success code. Returning '0'." + $exitCode = 0 + } } - } - Write-Debug "Finishing '$($MyInvocation.InvocationName)'" + Write-Debug "Finishing '$($MyInvocation.InvocationName)'" - return $exitCode + return $exitCode } Set-Alias Start-ChocolateyProcess Start-ChocolateyProcessAsAdmin diff --git a/src/chocolatey.resources/helpers/functions/Test-ProcessAdminRights.ps1 b/src/chocolatey.resources/helpers/functions/Test-ProcessAdminRights.ps1 index f8c031dc49..41c4ee620e 100644 --- a/src/chocolatey.resources/helpers/functions/Test-ProcessAdminRights.ps1 +++ b/src/chocolatey.resources/helpers/functions/Test-ProcessAdminRights.ps1 @@ -15,7 +15,7 @@ # limitations under the License. function Test-ProcessAdminRights { -<# + <# .SYNOPSIS Tests whether the current process is running with administrative rights. @@ -36,12 +36,12 @@ None System.Boolean #> - # do not log function call - ## Called from chocolateysetup.psm1 - wrap any Write-Host in try/catch + # do not log function call + ## Called from chocolateysetup.psm1 - wrap any Write-Host in try/catch - $currentPrincipal = New-Object Security.Principal.WindowsPrincipal([Security.Principal.WindowsIdentity]::GetCurrent([Security.Principal.TokenAccessLevels]'Query,Duplicate')) - $isAdmin = $currentPrincipal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator) - Write-Debug "Test-ProcessAdminRights: returning $isAdmin" + $currentPrincipal = New-Object Security.Principal.WindowsPrincipal([Security.Principal.WindowsIdentity]::GetCurrent([Security.Principal.TokenAccessLevels]'Query,Duplicate')) + $isAdmin = $currentPrincipal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator) + Write-Debug "Test-ProcessAdminRights: returning $isAdmin" - return $isAdmin + return $isAdmin } diff --git a/src/chocolatey.resources/helpers/functions/UnInstall-ChocolateyZipPackage.ps1 b/src/chocolatey.resources/helpers/functions/UnInstall-ChocolateyZipPackage.ps1 index 2a8ea90c82..d84bb505f4 100644 --- a/src/chocolatey.resources/helpers/functions/UnInstall-ChocolateyZipPackage.ps1 +++ b/src/chocolatey.resources/helpers/functions/UnInstall-ChocolateyZipPackage.ps1 @@ -15,7 +15,7 @@ # limitations under the License. function Uninstall-ChocolateyZipPackage { -<# + <# .SYNOPSIS Uninstalls a previous installed zip package, may not be necessary. @@ -55,30 +55,30 @@ Install-ChocolateyZipPackage .LINK Uninstall-ChocolateyPackage #> -param( - [parameter(Mandatory=$true, Position=0)][string] $packageName, - [parameter(Mandatory=$true, Position=1)][string] $zipFileName, - [parameter(ValueFromRemainingArguments = $true)][Object[]] $ignoredArguments -) - - Write-FunctionCallLogMessage -Invocation $MyInvocation -Parameters $PSBoundParameters - - $packagelibPath=$env:chocolateyPackageFolder - $zipContentFile=(join-path $packagelibPath $zipFileName) + "Install.txt" - - # The Zip Content File may have previously existed under a different - # name. If *Install.txt doesn't exist, check for the old name - if(-Not (Test-Path -Path $zipContentFile)) { - $zipContentFile=(Join-Path $packagelibPath -ChildPath $zipFileName) + ".txt" - } - - if ((Test-Path -path $zipContentFile)) { - $zipContentFile - $zipContents=get-content $zipContentFile - foreach ($fileInZip in $zipContents) { - if ($fileInZip -ne $null -and $fileInZip.Trim() -ne '') { - Remove-Item -Path "$fileInZip" -ErrorAction SilentlyContinue -Recurse -Force - } + param( + [parameter(Mandatory = $true, Position = 0)][string] $packageName, + [parameter(Mandatory = $true, Position = 1)][string] $zipFileName, + [parameter(ValueFromRemainingArguments = $true)][Object[]] $ignoredArguments + ) + + Write-FunctionCallLogMessage -Invocation $MyInvocation -Parameters $PSBoundParameters + + $packagelibPath = $env:chocolateyPackageFolder + $zipContentFile = (Join-Path $packagelibPath $zipFileName) + "Install.txt" + + # The Zip Content File may have previously existed under a different + # name. If *Install.txt doesn't exist, check for the old name + if (-Not (Test-Path -Path $zipContentFile)) { + $zipContentFile = (Join-Path $packagelibPath -ChildPath $zipFileName) + ".txt" + } + + if ((Test-Path -Path $zipContentFile)) { + $zipContentFile + $zipContents = Get-Content $zipContentFile + foreach ($fileInZip in $zipContents) { + if ($fileInZip -ne $null -and $fileInZip.Trim() -ne '') { + Remove-Item -Path "$fileInZip" -ErrorAction SilentlyContinue -Recurse -Force + } + } } - } } diff --git a/src/chocolatey.resources/helpers/functions/Uninstall-BinFile.ps1 b/src/chocolatey.resources/helpers/functions/Uninstall-BinFile.ps1 index b85438b032..bc63888880 100644 --- a/src/chocolatey.resources/helpers/functions/Uninstall-BinFile.ps1 +++ b/src/chocolatey.resources/helpers/functions/Uninstall-BinFile.ps1 @@ -15,7 +15,7 @@ # limitations under the License. function Uninstall-BinFile { -<# + <# .SYNOPSIS Removes a shim (or batch redirect) for a file. @@ -52,48 +52,48 @@ Allows splatting with arguments that do not apply. Do not use directly. .LINK Install-BinFile #> -param( - [parameter(Mandatory=$true, Position=0)][string] $name, - [parameter(Mandatory=$false, Position=1)][string] $path, - [parameter(ValueFromRemainingArguments = $true)][Object[]] $ignoredArguments -) - - Write-FunctionCallLogMessage -Invocation $MyInvocation -Parameters $PSBoundParameters - - $nugetPath = [System.IO.Path]::GetFullPath((Join-Path "$helpersPath" '..\')) - $nugetExePath = Join-Path "$nugetPath" 'bin' - $packageBatchFileName = Join-Path $nugetExePath "$name.bat" - $packageBashFileName = Join-Path $nugetExePath "$name" - $packageShimFileName = Join-Path $nugetExePath "$name.exe" - $path = $path.ToLower().Replace($nugetPath.ToLower(), "%DIR%..\").Replace("\\","\") - $pathBash = $path.Replace("%DIR%..\","`$DIR/../").Replace("\","/") - - Write-Debug "Attempting to remove the batch and bash shortcuts: $packageBatchFileName and $packageBashFileName" - - if (Test-Path $packageBatchFileName) { - Write-Host "Removing batch file $packageBatchFileName which pointed to `'$path`'." - Remove-Item $packageBatchFileName - } - else { - Write-Debug "Tried to remove batch file $packageBatchFileName but it was already removed." - } - - if (Test-Path $packageBashFileName) { - Write-Host "Removing bash file $packageBashFileName which pointed to `'$path`'." - Remove-Item $packageBashFileName - } - else { - Write-Debug "Tried to remove bash file $packageBashFileName but it was already removed." - } - - Write-Debug "Attempting to remove the shim: $packageShimFileName" - if (Test-Path $packageShimFileName) { - Write-Host "Removing shim $packageShimFileName which pointed to `'$path`'." - Remove-Item $packageShimFileName - } - else { - Write-Debug "Tried to remove shim $packageShimFileName but it was already removed." - } + param( + [parameter(Mandatory = $true, Position = 0)][string] $name, + [parameter(Mandatory = $false, Position = 1)][string] $path, + [parameter(ValueFromRemainingArguments = $true)][Object[]] $ignoredArguments + ) + + Write-FunctionCallLogMessage -Invocation $MyInvocation -Parameters $PSBoundParameters + + $nugetPath = [System.IO.Path]::GetFullPath((Join-Path "$helpersPath" '..\')) + $nugetExePath = Join-Path "$nugetPath" 'bin' + $packageBatchFileName = Join-Path $nugetExePath "$name.bat" + $packageBashFileName = Join-Path $nugetExePath "$name" + $packageShimFileName = Join-Path $nugetExePath "$name.exe" + $path = $path.ToLower().Replace($nugetPath.ToLower(), "%DIR%..\").Replace("\\", "\") + $pathBash = $path.Replace("%DIR%..\", "`$DIR/../").Replace("\", "/") + + Write-Debug "Attempting to remove the batch and bash shortcuts: $packageBatchFileName and $packageBashFileName" + + if (Test-Path $packageBatchFileName) { + Write-Host "Removing batch file $packageBatchFileName which pointed to `'$path`'." + Remove-Item $packageBatchFileName + } + else { + Write-Debug "Tried to remove batch file $packageBatchFileName but it was already removed." + } + + if (Test-Path $packageBashFileName) { + Write-Host "Removing bash file $packageBashFileName which pointed to `'$path`'." + Remove-Item $packageBashFileName + } + else { + Write-Debug "Tried to remove bash file $packageBashFileName but it was already removed." + } + + Write-Debug "Attempting to remove the shim: $packageShimFileName" + if (Test-Path $packageShimFileName) { + Write-Host "Removing shim $packageShimFileName which pointed to `'$path`'." + Remove-Item $packageShimFileName + } + else { + Write-Debug "Tried to remove shim $packageShimFileName but it was already removed." + } } Set-Alias Remove-BinFile Uninstall-BinFile diff --git a/src/chocolatey.resources/helpers/functions/Uninstall-ChocolateyEnvironmentVariable.ps1 b/src/chocolatey.resources/helpers/functions/Uninstall-ChocolateyEnvironmentVariable.ps1 index 10a91d6bab..da05f114fa 100644 --- a/src/chocolatey.resources/helpers/functions/Uninstall-ChocolateyEnvironmentVariable.ps1 +++ b/src/chocolatey.resources/helpers/functions/Uninstall-ChocolateyEnvironmentVariable.ps1 @@ -15,7 +15,7 @@ # limitations under the License. function Uninstall-ChocolateyEnvironmentVariable { -<# + <# .SYNOPSIS **NOTE:** Administrative Access Required when `-VariableType 'Machine'.` @@ -71,25 +71,27 @@ Set-EnvironmentVariable .LINK Install-ChocolateyPath #> -param( - [parameter(Mandatory=$true, Position=0)][string] $variableName, - [parameter(Mandatory=$false, Position=1)] - [System.EnvironmentVariableTarget] $variableType = [System.EnvironmentVariableTarget]::User, - [parameter(ValueFromRemainingArguments = $true)][Object[]] $ignoredArguments -) - - Write-FunctionCallLogMessage -Invocation $MyInvocation -Parameters $PSBoundParameters - - if ($variableType -eq [System.EnvironmentVariableTarget]::Machine) { - if (Test-ProcessAdminRights) { - Set-EnvironmentVariable -Name $variableName -Value $null -Scope $variableType - } else { - $psArgs = "Install-ChocolateyEnvironmentVariable -variableName `'$variableName`' -variableValue $null -variableType `'$variableType`'" - Start-ChocolateyProcessAsAdmin "$psArgs" + param( + [parameter(Mandatory = $true, Position = 0)][string] $variableName, + [parameter(Mandatory = $false, Position = 1)] + [System.EnvironmentVariableTarget] $variableType = [System.EnvironmentVariableTarget]::User, + [parameter(ValueFromRemainingArguments = $true)][Object[]] $ignoredArguments + ) + + Write-FunctionCallLogMessage -Invocation $MyInvocation -Parameters $PSBoundParameters + + if ($variableType -eq [System.EnvironmentVariableTarget]::Machine) { + if (Test-ProcessAdminRights) { + Set-EnvironmentVariable -Name $variableName -Value $null -Scope $variableType + } + else { + $psArgs = "Install-ChocolateyEnvironmentVariable -variableName `'$variableName`' -variableValue $null -variableType `'$variableType`'" + Start-ChocolateyProcessAsAdmin "$psArgs" + } + } + else { + Set-EnvironmentVariable -Name $variableName -Value $null -Scope $variableType } - } else { - Set-EnvironmentVariable -Name $variableName -Value $null -Scope $variableType - } - Set-Content env:\$variableName $null + Set-Content env:\$variableName $null } diff --git a/src/chocolatey.resources/helpers/functions/Uninstall-ChocolateyPackage.ps1 b/src/chocolatey.resources/helpers/functions/Uninstall-ChocolateyPackage.ps1 index 992d1ccf16..91868cd957 100644 --- a/src/chocolatey.resources/helpers/functions/Uninstall-ChocolateyPackage.ps1 +++ b/src/chocolatey.resources/helpers/functions/Uninstall-ChocolateyPackage.ps1 @@ -15,7 +15,7 @@ # limitations under the License. function Uninstall-ChocolateyPackage { -<# + <# .SYNOPSIS Uninstalls software from "Programs and Features". @@ -106,52 +106,58 @@ Uninstall-ChocolateyZipPackage .LINK Get-UninstallRegistryKey #> -param( - [parameter(Mandatory=$true, Position=0)][string] $packageName, - [parameter(Mandatory=$false, Position=1)] - [alias("installerType")][string] $fileType = 'exe', - [parameter(Mandatory=$false, Position=2)][string[]] $silentArgs = '', - [parameter(Mandatory=$false, Position=3)][string] $file, - [parameter(Mandatory=$false)] $validExitCodes = @(0), - [parameter(ValueFromRemainingArguments = $true)][Object[]] $ignoredArguments -) - [string]$silentArgs = $silentArgs -join ' ' - - Write-FunctionCallLogMessage -Invocation $MyInvocation -Parameters $PSBoundParameters - - $installMessage = "Uninstalling $packageName..." - write-host $installMessage - - $additionalInstallArgs = $env:chocolateyInstallArguments; - if ($additionalInstallArgs -eq $null) { $additionalInstallArgs = ''; } - $overrideArguments = $env:chocolateyInstallOverride; - - if ($fileType -eq $null) { $fileType = '' } - $installerTypeLower = $fileType.ToLower() - if ($installerTypeLower -ne 'msi' -and $installerTypeLower -ne 'exe') { - Write-Warning "FileType '$fileType' is unrecognized, using 'exe' instead." - $fileType = 'exe' - } - - if ($fileType -like 'msi') { - $msiArgs = "/x" - if ($overrideArguments) { - $msiArgs = "$msiArgs $additionalInstallArgs"; - write-host "Overriding package arguments with `'$additionalInstallArgs`'"; - } else { - $msiArgs = "$msiArgs $silentArgs $additionalInstallArgs"; + param( + [parameter(Mandatory = $true, Position = 0)][string] $packageName, + [parameter(Mandatory = $false, Position = 1)] + [alias("installerType")][string] $fileType = 'exe', + [parameter(Mandatory = $false, Position = 2)][string[]] $silentArgs = '', + [parameter(Mandatory = $false, Position = 3)][string] $file, + [parameter(Mandatory = $false)] $validExitCodes = @(0), + [parameter(ValueFromRemainingArguments = $true)][Object[]] $ignoredArguments + ) + [string]$silentArgs = $silentArgs -join ' ' + + Write-FunctionCallLogMessage -Invocation $MyInvocation -Parameters $PSBoundParameters + + $installMessage = "Uninstalling $packageName..." + Write-Host $installMessage + + $additionalInstallArgs = $env:chocolateyInstallArguments; + if ($additionalInstallArgs -eq $null) { + $additionalInstallArgs = ''; } + $overrideArguments = $env:chocolateyInstallOverride; - Start-ChocolateyProcessAsAdmin "$msiArgs" "$($env:SystemRoot)\System32\msiexec.exe" -validExitCodes $validExitCodes - } - if ($fileType -like 'exe') { - if ($overrideArguments) { - Write-Host "Overriding package arguments with `'$additionalInstallArgs`'"; - Start-ChocolateyProcessAsAdmin "$additionalInstallArgs" $file -validExitCodes $validExitCodes - } else { - Start-ChocolateyProcessAsAdmin "$silentArgs $additionalInstallArgs" $file -validExitCodes $validExitCodes + if ($fileType -eq $null) { + $fileType = '' + } + $installerTypeLower = $fileType.ToLower() + if ($installerTypeLower -ne 'msi' -and $installerTypeLower -ne 'exe') { + Write-Warning "FileType '$fileType' is unrecognized, using 'exe' instead." + $fileType = 'exe' + } + + if ($fileType -like 'msi') { + $msiArgs = "/x" + if ($overrideArguments) { + $msiArgs = "$msiArgs $additionalInstallArgs"; + Write-Host "Overriding package arguments with `'$additionalInstallArgs`'"; + } + else { + $msiArgs = "$msiArgs $silentArgs $additionalInstallArgs"; + } + + Start-ChocolateyProcessAsAdmin "$msiArgs" "$($env:SystemRoot)\System32\msiexec.exe" -validExitCodes $validExitCodes + } + if ($fileType -like 'exe') { + if ($overrideArguments) { + Write-Host "Overriding package arguments with `'$additionalInstallArgs`'"; + Start-ChocolateyProcessAsAdmin "$additionalInstallArgs" $file -validExitCodes $validExitCodes + } + else { + Start-ChocolateyProcessAsAdmin "$silentArgs $additionalInstallArgs" $file -validExitCodes $validExitCodes + } } - } - Write-Host "$packageName has been uninstalled." + Write-Host "$packageName has been uninstalled." } diff --git a/src/chocolatey.resources/helpers/functions/Update-SessionEnvironment.ps1 b/src/chocolatey.resources/helpers/functions/Update-SessionEnvironment.ps1 index 0c89dca3ec..964406dc45 100644 --- a/src/chocolatey.resources/helpers/functions/Update-SessionEnvironment.ps1 +++ b/src/chocolatey.resources/helpers/functions/Update-SessionEnvironment.ps1 @@ -15,7 +15,7 @@ # limitations under the License. function Update-SessionEnvironment { -<# + <# .SYNOPSIS Updates the environment variables of the current powershell session with any environment variable changes that may have occurred during a @@ -47,55 +47,60 @@ None None #> - Write-FunctionCallLogMessage -Invocation $MyInvocation -Parameters $PSBoundParameters - - $refreshEnv = $false - $invocation = $MyInvocation - if ($invocation.InvocationName -eq 'refreshenv') { - $refreshEnv = $true - } - - if ($refreshEnv) { - Write-Output 'Refreshing environment variables from the registry for powershell.exe. Please wait...' - } else { - Write-Verbose 'Refreshing environment variables from the registry.' - } - - $userName = $env:USERNAME - $architecture = $env:PROCESSOR_ARCHITECTURE - $psModulePath = $env:PSModulePath - - #ordering is important here, $user should override $machine... - $ScopeList = 'Process', 'Machine' - if ('SYSTEM', "${env:COMPUTERNAME}`$" -notcontains $userName) { - # but only if not running as the SYSTEM/machine in which case user can be ignored. - $ScopeList += 'User' - } - foreach ($Scope in $ScopeList) { - Get-EnvironmentVariableNames -Scope $Scope | + Write-FunctionCallLogMessage -Invocation $MyInvocation -Parameters $PSBoundParameters + + $refreshEnv = $false + $invocation = $MyInvocation + if ($invocation.InvocationName -eq 'refreshenv') { + $refreshEnv = $true + } + + if ($refreshEnv) { + Write-Output 'Refreshing environment variables from the registry for powershell.exe. Please wait...' + } + else { + Write-Verbose 'Refreshing environment variables from the registry.' + } + + $userName = $env:USERNAME + $architecture = $env:PROCESSOR_ARCHITECTURE + $psModulePath = $env:PSModulePath + + #ordering is important here, $user should override $machine... + $ScopeList = 'Process', 'Machine' + if ('SYSTEM', "${env:COMPUTERNAME}`$" -notcontains $userName) { + # but only if not running as the SYSTEM/machine in which case user can be ignored. + $ScopeList += 'User' + } + foreach ($Scope in $ScopeList) { + Get-EnvironmentVariableNames -Scope $Scope | + ForEach-Object { + Set-Item "Env:$_" -Value (Get-EnvironmentVariable -Scope $Scope -Name $_) + } + } + + #Path gets special treatment b/c it munges the two together + $paths = 'Machine', 'User' | ForEach-Object { - Set-Item "Env:$_" -Value (Get-EnvironmentVariable -Scope $Scope -Name $_) - } - } - - #Path gets special treatment b/c it munges the two together - $paths = 'Machine', 'User' | - ForEach-Object { (Get-EnvironmentVariable -Name 'PATH' -Scope $_) -split ';' - } | - Select-Object -Unique - $Env:PATH = $paths -join ';' - - # PSModulePath is almost always updated by process, so we want to preserve it. - $env:PSModulePath = $psModulePath - - # reset user and architecture - if ($userName) { $env:USERNAME = $userName; } - if ($architecture) { $env:PROCESSOR_ARCHITECTURE = $architecture; } - - if ($refreshEnv) { - Write-Output 'Finished' - } + } | + Select-Object -Unique + $Env:PATH = $paths -join ';' + + # PSModulePath is almost always updated by process, so we want to preserve it. + $env:PSModulePath = $psModulePath + + # reset user and architecture + if ($userName) { + $env:USERNAME = $userName; + } + if ($architecture) { + $env:PROCESSOR_ARCHITECTURE = $architecture; + } + + if ($refreshEnv) { + Write-Output 'Finished' + } } Set-Alias refreshenv Update-SessionEnvironment diff --git a/src/chocolatey.resources/helpers/functions/Write-FunctionCallLogMessage.ps1 b/src/chocolatey.resources/helpers/functions/Write-FunctionCallLogMessage.ps1 index adfd063d49..2cb2800344 100644 --- a/src/chocolatey.resources/helpers/functions/Write-FunctionCallLogMessage.ps1 +++ b/src/chocolatey.resources/helpers/functions/Write-FunctionCallLogMessage.ps1 @@ -15,7 +15,7 @@ # limitations under the License. function Write-FunctionCallLogMessage { -<# + <# .SYNOPSIS DO NOT USE. Not part of the public API. @@ -48,23 +48,25 @@ Allows splatting with arguments that do not apply. Do not use directly. Write-FunctionCallLogMessage -Invocation $MyInvocation -Parameters $PSBoundParameters #> -param ( - $invocation, - $parameters, - [parameter(ValueFromRemainingArguments = $true)][Object[]] $ignoredArguments -) + param ( + $invocation, + $parameters, + [parameter(ValueFromRemainingArguments = $true)][Object[]] $ignoredArguments + ) - # do not log function call - recursion? + # do not log function call - recursion? - $argumentsPassed = '' - foreach ($param in $parameters.GetEnumerator()) { - if ($param.Key -eq 'ignoredArguments') { continue; } - $paramValue = $param.Value -Join ' ' - if ($param.Key -eq 'sensitiveStatements' -or $param.Key -eq 'password') { - $paramValue = '[REDACTED]' + $argumentsPassed = '' + foreach ($param in $parameters.GetEnumerator()) { + if ($param.Key -eq 'ignoredArguments') { + continue; + } + $paramValue = $param.Value -Join ' ' + if ($param.Key -eq 'sensitiveStatements' -or $param.Key -eq 'password') { + $paramValue = '[REDACTED]' + } + $argumentsPassed += "-$($param.Key) '$paramValue' " } - $argumentsPassed += "-$($param.Key) '$paramValue' " - } - Write-Debug "Running $($invocation.InvocationName) $argumentsPassed" + Write-Debug "Running $($invocation.InvocationName) $argumentsPassed" } diff --git a/src/chocolatey.tests.integration/context/badpackage/1.0/tools/chocolateyInstall.ps1 b/src/chocolatey.tests.integration/context/badpackage/1.0/tools/chocolateyInstall.ps1 index 0c3f138571..56347ff256 100644 --- a/src/chocolatey.tests.integration/context/badpackage/1.0/tools/chocolateyInstall.ps1 +++ b/src/chocolatey.tests.integration/context/badpackage/1.0/tools/chocolateyInstall.ps1 @@ -1,6 +1,6 @@ -$toolsDir = "$(Split-Path -parent $MyInvocation.MyCommand.Definition)" +$toolsDir = "$(Split-Path -Parent $MyInvocation.MyCommand.Definition)" -"simple file" | Out-File "$toolsDir\simplefile.txt" -force +"simple file" | Out-File "$toolsDir\simplefile.txt" -Force Write-Output "This is $packageName v$packageVersion being installed to `n '$packageFolder'." Write-Host "PowerShell Version is '$($PSVersionTable.PSVersion)' and CLR Version is '$($PSVersionTable.CLRVersion)'." diff --git a/src/chocolatey.tests.integration/context/installpackage/1.0.0/tools/chocolateyinstall.ps1 b/src/chocolatey.tests.integration/context/installpackage/1.0.0/tools/chocolateyinstall.ps1 index 53b064d5b7..21ed994ac8 100644 --- a/src/chocolatey.tests.integration/context/installpackage/1.0.0/tools/chocolateyinstall.ps1 +++ b/src/chocolatey.tests.integration/context/installpackage/1.0.0/tools/chocolateyinstall.ps1 @@ -1,5 +1,5 @@ -$toolsDir = "$(Split-Path -parent $MyInvocation.MyCommand.Definition)" -"simple file" | Out-File "$toolsDir\simplefile.txt" -force +$toolsDir = "$(Split-Path -Parent $MyInvocation.MyCommand.Definition)" +"simple file" | Out-File "$toolsDir\simplefile.txt" -Force Write-Output "This is $packageName v$packageVersion being installed to `n $packageFolder" Write-Host "Ya!" diff --git a/tests/chocolatey-tests/chocolatey.Tests.ps1 b/tests/chocolatey-tests/chocolatey.Tests.ps1 index de3a47c88a..ea012b3ac9 100644 --- a/tests/chocolatey-tests/chocolatey.Tests.ps1 +++ b/tests/chocolatey-tests/chocolatey.Tests.ps1 @@ -110,7 +110,7 @@ Describe "Ensuring Chocolatey is correctly installed" -Tag Environment, Chocolat } # This is skipped when not run in CI because it requires signed executables. - Context "File signing (<_.FullName>)" -Foreach @($PowerShellFiles; $ExecutableFiles; $StrongNamingKeyFiles) -Skip:((-not $env:TEST_KITCHEN) -or (-not (Test-ChocolateyVersionEqualOrHigherThan "1.0.0"))) { + Context "File signing (<_.FullName>)" -ForEach @($PowerShellFiles; $ExecutableFiles; $StrongNamingKeyFiles) -Skip:((-not $env:TEST_KITCHEN) -or (-not (Test-ChocolateyVersionEqualOrHigherThan "1.0.0"))) { BeforeAll { $FileUnderTest = $_ $SignerCert = (Get-AuthenticodeSignature (Get-ChocoPath)).SignerCertificate @@ -146,7 +146,7 @@ Describe "Ensuring Chocolatey is correctly installed" -Tag Environment, Chocolat } } - Context "PowerShell script formatting (<_.FullName>)" -Foreach $PowerShellFiles { + Context "PowerShell script formatting (<_.FullName>)" -ForEach $PowerShellFiles { BeforeAll { $FileUnderTest = $_ } @@ -258,7 +258,7 @@ Describe "Ensuring Chocolatey is correctly installed" -Tag Environment, Chocolat } # This is skipped when not run in CI because it requires signed executables - Context 'Ensure we shims during upgrade' -Skip:((-not $env:TEST_KITCHEN) -or (-not (Test-ChocolateyVersionEqualOrHigherThan '1.0.0'))) -Foreach @( + Context 'Ensure we shims during upgrade' -Skip:((-not $env:TEST_KITCHEN) -or (-not (Test-ChocolateyVersionEqualOrHigherThan '1.0.0'))) -ForEach @( @{ RemovedShims = $RemovedShims Signed = $true @@ -320,7 +320,7 @@ Describe "Ensuring Chocolatey is correctly installed" -Tag Environment, Chocolat } # This is skipped when not run in CI because it modifies the local system. - Context 'Get-FileEncoding works under <_>' -Tag PowerShell7 -Foreach @( + Context 'Get-FileEncoding works under <_>' -Tag PowerShell7 -ForEach @( 'pwsh' 'powershell' ) -Skip:((-not $env:TEST_KITCHEN) -or (-not (Test-ChocolateyVersionEqualOrHigherThan '1.1.0'))) { diff --git a/tests/chocolatey-tests/commands/choco-apikey.Tests.ps1 b/tests/chocolatey-tests/commands/choco-apikey.Tests.ps1 index 9b2d540324..0a57d74373 100644 --- a/tests/chocolatey-tests/commands/choco-apikey.Tests.ps1 +++ b/tests/chocolatey-tests/commands/choco-apikey.Tests.ps1 @@ -171,7 +171,6 @@ Describe "choco <_>" -ForEach $Command -Tag Chocolatey, ApiKeyCommand { It "Removed apikey do not exist in file" -Skip { $config = $apiKeys.Where{ $_.source -eq "https://remove.test.com/api" } $config | Should -BeNullOrEmpty - } } diff --git a/tests/chocolatey-tests/commands/choco-config.Tests.ps1 b/tests/chocolatey-tests/commands/choco-config.Tests.ps1 index 85dbd4be52..71e21ccefd 100644 --- a/tests/chocolatey-tests/commands/choco-config.Tests.ps1 +++ b/tests/chocolatey-tests/commands/choco-config.Tests.ps1 @@ -146,7 +146,12 @@ Describe "choco config" -Tag Chocolatey, ConfigCommand { It "Displays Available Sources - " -ForEach @( @{ Name = "chocolatey" - Source = if (Test-ChocolateyVersionEqualOrHigherThan "0.10.16-beta") { "https://community.chocolatey.org/api/v2/" } else { "https://chocolatey.org/api/v2/" } + Source = if (Test-ChocolateyVersionEqualOrHigherThan "0.10.16-beta") { + "https://community.chocolatey.org/api/v2/" + } + else { + "https://chocolatey.org/api/v2/" + } } ) { $Output.String | Should -MatchExactly "$Name( \[Disabled\])? - $([Regex]::Escape($Source))\s*\|" diff --git a/tests/chocolatey-tests/commands/choco-deprecated.Tests.ps1 b/tests/chocolatey-tests/commands/choco-deprecated.Tests.ps1 index 1ef836046f..14561d1c42 100644 --- a/tests/chocolatey-tests/commands/choco-deprecated.Tests.ps1 +++ b/tests/chocolatey-tests/commands/choco-deprecated.Tests.ps1 @@ -22,7 +22,7 @@ Describe "choco deprecated shims" -Skip:(-not (Test-ChocolateyVersionEqualOrHigh ) } - Context 'help for command mentions that is deprecated' -Foreach $DeprecatedShims { + Context 'help for command mentions that is deprecated' -ForEach $DeprecatedShims { BeforeAll { # -? needs to be wrapped in quotes or PowerShell consumes it on us. $Output = Invoke-Choco $Command "-?" diff --git a/tests/chocolatey-tests/commands/choco-export.Tests.ps1 b/tests/chocolatey-tests/commands/choco-export.Tests.ps1 index 55a7f487a1..64662a37a1 100644 --- a/tests/chocolatey-tests/commands/choco-export.Tests.ps1 +++ b/tests/chocolatey-tests/commands/choco-export.Tests.ps1 @@ -90,19 +90,19 @@ Describe "choco export" -Tag Chocolatey, ExportCommand { $Output.Lines | Should -Contain "choco export []" } - It "Displays example '<_>'" -Foreach $examples { + It "Displays example '<_>'" -ForEach $examples { $Output.Lines | Should -Contain $_ } - It "Displays supported exit codes" -Foreach $supportedExitCodes { + It "Displays supported exit codes" -ForEach $supportedExitCodes { $Output.Lines | Should -Contain $_ } - It "Displays supported option and switches " -Foreach $supportedArguments { + It "Displays supported option and switches " -ForEach $supportedArguments { $Output.Lines | Should -Contain $Arguments } - It "Displays description of option and switches " -Foreach $supportedArguments { + It "Displays description of option and switches " -ForEach $supportedArguments { $Description -split "`n" | ForEach-Object { $Output.Lines | Should -Contain $_ } @@ -140,12 +140,12 @@ Describe "choco export" -Tag Chocolatey, ExportCommand { $Output.Lines | Should -Contain $expectedHeader } - It "Exports expected package '<_>'" -Foreach $expectedExports { + It "Exports expected package '<_>'" -ForEach $expectedExports { $expectedPath | Should -FileContentMatch "" } } - Context "Runs export with including versions (<_>)" -Foreach @("--include-version-numbers", "--include-version") { + Context "Runs export with including versions (<_>)" -ForEach @("--include-version-numbers", "--include-version") { BeforeDiscovery { # TODO: Consolidate these recurring package lists - https://github.com/chocolatey/choco/issues/2691 # We set this here, so we can reuse them between different contexts @@ -191,7 +191,7 @@ Describe "choco export" -Tag Chocolatey, ExportCommand { $Output.Lines | Should -Contain $expectedHeader } - It "Exports expected package '' with version ''" -Foreach $expectedExports { + It "Exports expected package '' with version ''" -ForEach $expectedExports { $expectedPath | Should -FileContentMatch "" } @@ -233,12 +233,12 @@ Describe "choco export" -Tag Chocolatey, ExportCommand { $Output.Lines | Should -Contain $expectedHeader } - It "Exports expected package '<_>'" -Foreach $expectedExports { + It "Exports expected package '<_>'" -ForEach $expectedExports { $expectedPath | Should -FileContentMatch "" } } - Context "Runs export with including versions (<_>)" -Foreach @("--include-version-numbers", "--include-version") { + Context "Runs export with including versions (<_>)" -ForEach @("--include-version-numbers", "--include-version") { BeforeDiscovery { # TODO: Consolidate these recurring package lists - https://github.com/chocolatey/choco/issues/2691 # We set this here, so we can reuse them between different contexts @@ -284,7 +284,7 @@ Describe "choco export" -Tag Chocolatey, ExportCommand { $Output.Lines | Should -Contain $expectedHeader } - It "Exports expected package '' with version ''" -Foreach $expectedExports { + It "Exports expected package '' with version ''" -ForEach $expectedExports { $expectedPath | Should -FileContentMatch "" } @@ -294,7 +294,7 @@ Describe "choco export" -Tag Chocolatey, ExportCommand { } } - Context "Runs export with output path argument '<_>" -Foreach @("--output-file-path={0}"; "-o {0}") { + Context "Runs export with output path argument '<_>" -ForEach @("--output-file-path={0}"; "-o {0}") { BeforeDiscovery { # TODO: Consolidate these recurring package lists - https://github.com/chocolatey/choco/issues/2691 # We set this here, so we can reuse them between different contexts @@ -326,12 +326,12 @@ Describe "choco export" -Tag Chocolatey, ExportCommand { $Output.Lines | Should -Contain $expectedHeader } - It "Exports expected package '<_>'" -Foreach $expectedExports { + It "Exports expected package '<_>'" -ForEach $expectedExports { $expectedPath | Should -FileContentMatch "" } } - Context "Runs export with path argument () including versions ()" -Foreach @( + Context "Runs export with path argument () including versions ()" -ForEach @( @{ PathArgument = "--output-file-path={0}" VersionsArgument = "--include-version-numbers" @@ -394,7 +394,7 @@ Describe "choco export" -Tag Chocolatey, ExportCommand { $Output.Lines | Should -Contain $expectedHeader } - It "Exports expected package '' with version ''" -Foreach $expectedExports { + It "Exports expected package '' with version ''" -ForEach $expectedExports { $expectedPath | Should -FileContentMatch "" } diff --git a/tests/chocolatey-tests/commands/choco-feature.Tests.ps1 b/tests/chocolatey-tests/commands/choco-feature.Tests.ps1 index 34de48fea6..ceaabbd364 100644 --- a/tests/chocolatey-tests/commands/choco-feature.Tests.ps1 +++ b/tests/chocolatey-tests/commands/choco-feature.Tests.ps1 @@ -66,14 +66,14 @@ Describe "choco <_>" -ForEach $Command -Tag Chocolatey, FeatureCommand { # Get the features this way so we're working with the entire list, and not just what was in the config file initially. # We additionally want to ignore any presence of removed features # as these are not intended to work as expected, even when present. - $FeaturesToTest = (Invoke-Choco feature list -r).Lines | ConvertFrom-ChocolateyOutput -Command Feature | Where-Object Name -ne 'scriptsCheckLastExitCode' + $FeaturesToTest = (Invoke-Choco feature list -r).Lines | ConvertFrom-ChocolateyOutput -Command Feature | Where-Object Name -NE 'scriptsCheckLastExitCode' } BeforeAll { Restore-ChocolateyInstallSnapshot } - Context "Enabling <_.Name> feature" -Foreach $FeaturesToTest { + Context "Enabling <_.Name> feature" -ForEach $FeaturesToTest { BeforeAll { $Name = $_.Name # Disable feature before trying to enable it. @@ -90,7 +90,7 @@ Describe "choco <_>" -ForEach $Command -Tag Chocolatey, FeatureCommand { } } - Context "Disabling <_.Name> feature" -Foreach $FeaturesToTest { + Context "Disabling <_.Name> feature" -ForEach $FeaturesToTest { BeforeAll { $Name = $_.Name # Enable feature before trying to enable it. diff --git a/tests/chocolatey-tests/commands/choco-help.Tests.ps1 b/tests/chocolatey-tests/commands/choco-help.Tests.ps1 index f8e01f256c..564128b403 100644 --- a/tests/chocolatey-tests/commands/choco-help.Tests.ps1 +++ b/tests/chocolatey-tests/commands/choco-help.Tests.ps1 @@ -18,7 +18,7 @@ Import-Module helpers/common-helpers BeforeDiscovery { $AllTopLevelCommands = (Invoke-Choco $Command[0]).Lines -match " \* (?\w+) -" -replace " \* (?\w+) -.+", '$1' - $TopLevelCommands = $AllTopLevelCommands.Where{$_ -notin $SkipCommand} + $TopLevelCommands = $AllTopLevelCommands.Where{ $_ -notin $SkipCommand } } Describe "choco help sections with command <_>" -ForEach $Command -Tag Chocolatey, HelpCommand { @@ -51,7 +51,7 @@ Describe "choco help sections with command <_>" -ForEach $Command -Tag Chocolate } } - Context "choco <_> $helpArgument" -Foreach $TopLevelCommands { + Context "choco <_> $helpArgument" -ForEach $TopLevelCommands { BeforeDiscovery { $comandsWithoutExitCodes = @( "help" diff --git a/tests/chocolatey-tests/commands/choco-new.Tests.ps1 b/tests/chocolatey-tests/commands/choco-new.Tests.ps1 index a9eb9411d6..9f2f577a53 100644 --- a/tests/chocolatey-tests/commands/choco-new.Tests.ps1 +++ b/tests/chocolatey-tests/commands/choco-new.Tests.ps1 @@ -138,7 +138,7 @@ Describe "choco new" -Tag Chocolatey, NewCommand { } # https://github.com/chocolatey/choco/issues/1003 - Context "Create new package with template containing empty folders" -Foreach @{ EmptyFolders = $EmptyFolders } { + Context "Create new package with template containing empty folders" -ForEach @{ EmptyFolders = $EmptyFolders } { BeforeAll { New-ChocolateyInstallSnapshot -SetWorkDir diff --git a/tests/chocolatey-tests/commands/choco-outdated.Tests.ps1 b/tests/chocolatey-tests/commands/choco-outdated.Tests.ps1 index 982caff380..b6607b6b7d 100644 --- a/tests/chocolatey-tests/commands/choco-outdated.Tests.ps1 +++ b/tests/chocolatey-tests/commands/choco-outdated.Tests.ps1 @@ -22,7 +22,7 @@ Describe "choco outdated" -Tag Chocolatey, OutdatedCommand { Remove-ChocolateyTestInstall } - Context "outdated ignore-pinned uses correct enhanced exit codes" -Foreach @( + Context "outdated ignore-pinned uses correct enhanced exit codes" -ForEach @( @{ Argument = '' ; ExitCode = 2 } @{ Argument = '--ignore-pinned' ; ExitCode = 0 } ) -Skip:(-not (Test-ChocolateyVersionEqualOrHigherThan '1.1.0')) { diff --git a/tests/chocolatey-tests/commands/choco-push.Tests.ps1 b/tests/chocolatey-tests/commands/choco-push.Tests.ps1 index b2f39a1803..26377df8fd 100644 --- a/tests/chocolatey-tests/commands/choco-push.Tests.ps1 +++ b/tests/chocolatey-tests/commands/choco-push.Tests.ps1 @@ -39,8 +39,8 @@ Describe "choco push" -Tag Chocolatey, PushCommand -Skip:($null -eq $env:API_KEY $NewChocolateyTestPackage = @{ TestPath = "$PSScriptRoot\testpackages" - Name = $PackageUnderTest - Version = $VersionUnderTest + Name = $PackageUnderTest + Version = $VersionUnderTest } New-ChocolateyTestPackage @NewChocolateyTestPackage @@ -70,8 +70,8 @@ Describe "choco push" -Tag Chocolatey, PushCommand -Skip:($null -eq $env:API_KEY $NewChocolateyTestPackage = @{ TestPath = "$PSScriptRoot\testpackages" - Name = $PackageUnderTest - Version = $VersionUnderTest + Name = $PackageUnderTest + Version = $VersionUnderTest } New-ChocolateyTestPackage @NewChocolateyTestPackage @@ -101,8 +101,8 @@ Describe "choco push" -Tag Chocolatey, PushCommand -Skip:($null -eq $env:API_KEY $NewChocolateyTestPackage = @{ TestPath = "$PSScriptRoot\testpackages" - Name = $PackageUnderTest - Version = $VersionUnderTest + Name = $PackageUnderTest + Version = $VersionUnderTest } New-ChocolateyTestPackage @NewChocolateyTestPackage diff --git a/tests/chocolatey-tests/commands/choco-removed.Tests.ps1 b/tests/chocolatey-tests/commands/choco-removed.Tests.ps1 index 1a05b06f4f..adf902c8f4 100644 --- a/tests/chocolatey-tests/commands/choco-removed.Tests.ps1 +++ b/tests/chocolatey-tests/commands/choco-removed.Tests.ps1 @@ -12,7 +12,7 @@ Describe "Ensuring removed things are removed" -Tag Removed, Chocolatey { Remove-ChocolateyTestInstall } - Context 'Helper function ()' -Skip:(-not (Test-ChocolateyVersionEqualOrHigherThan '1.0.0')) -Foreach @( + Context 'Helper function ()' -Skip:(-not (Test-ChocolateyVersionEqualOrHigherThan '1.0.0')) -ForEach @( @{ FunctionName = 'Write-FileUpdateLog' } @{ FunctionName = 'Write-ChocolateySuccess' } @{ FunctionName = 'Write-ChocolateyFailure' } @@ -75,7 +75,7 @@ exit $command.Count } } - Context 'Ensure removed from Chocolatey' -Skip:(-not (Test-ChocolateyVersionEqualOrHigherThan '1.0.0')) -Foreach @( + Context 'Ensure removed from Chocolatey' -Skip:(-not (Test-ChocolateyVersionEqualOrHigherThan '1.0.0')) -ForEach @( @{ Command = 'update' } @{ Command = 'version' } ) { diff --git a/tests/chocolatey-tests/commands/choco-template.Tests.ps1 b/tests/chocolatey-tests/commands/choco-template.Tests.ps1 index b699fea6fc..6716f0ff39 100644 --- a/tests/chocolatey-tests/commands/choco-template.Tests.ps1 +++ b/tests/chocolatey-tests/commands/choco-template.Tests.ps1 @@ -5,7 +5,6 @@ Describe "choco <_>" -ForEach @( "templates" ) -Tag Chocolatey, TemplateCommand { BeforeDiscovery { - } BeforeAll { @@ -116,7 +115,7 @@ Describe "choco <_>" -ForEach @( $Output.Lines | Should -Contain 'List of Parameters:' } - It "Displays parameter name <_>" -Foreach @('PackageNameLower'; 'PackageVersion'; 'MaintainerRepo'; 'MaintainerName'; 'PackageName'; 'AutomaticPackageNotesNuspec'; 'AutomaticPackageNotesInstaller'; 'Url'; 'Url64'; 'Checksum'; 'Checksum64'; 'SilentArgs') { + It "Displays parameter name <_>" -ForEach @('PackageNameLower'; 'PackageVersion'; 'MaintainerRepo'; 'MaintainerName'; 'PackageName'; 'AutomaticPackageNotesNuspec'; 'AutomaticPackageNotesInstaller'; 'Url'; 'Url64'; 'Checksum'; 'Checksum64'; 'SilentArgs') { $Output.Lines | Should -Contain $_ } @@ -241,9 +240,9 @@ Describe "choco <_>" -ForEach @( } } - It "Displays template information for files" -Foreach @( + It "Displays template information for files" -ForEach @( @{ - Name = 'msi' + Name = 'msi' Files = @( 'msi\msi.nuspec' 'msi\ReadMe.md' @@ -255,7 +254,7 @@ Describe "choco <_>" -ForEach @( ) } @{ - Name = 'zip' + Name = 'zip' Files = @( 'zip\zip.nuspec' 'zip\ReadMe.md' @@ -280,19 +279,19 @@ Describe "choco <_>" -ForEach @( $items | Should -HaveCount 2 -Because $Output.String } - It "Displays parameter name <_>" -Foreach @('PackageNameLower'; 'PackageVersion'; 'MaintainerRepo'; 'MaintainerName'; 'PackageName'; 'AutomaticPackageNotesNuspec'; 'AutomaticPackageNotesInstaller'; 'Url'; 'Url64'; 'Checksum'; 'Checksum64') { + It "Displays parameter name <_>" -ForEach @('PackageNameLower'; 'PackageVersion'; 'MaintainerRepo'; 'MaintainerName'; 'PackageName'; 'AutomaticPackageNotesNuspec'; 'AutomaticPackageNotesInstaller'; 'Url'; 'Url64'; 'Checksum'; 'Checksum64') { $parameter = $_ $items = $Output.Lines | Where-Object { $_ -eq $parameter } $items | Should -HaveCount 2 -Because $Output.String } - It "Displays parameter name <_>" -Foreach @('SilentArgs') { + It "Displays parameter name <_>" -ForEach @('SilentArgs') { $parameter = $_ $items = $Output.Lines | Where-Object { $_ -eq $parameter } $items | Should -HaveCount 1 -Because $Output.String } - It "Created parameters file for <_>" -Foreach @('msi', 'zip') { + It "Created parameters file for <_>" -ForEach @('msi', 'zip') { "$env:ChocolateyInstall\templates\$_\.parameters" | Should -Exist } } diff --git a/tests/chocolatey-tests/commands/choco-uninstall.Tests.ps1 b/tests/chocolatey-tests/commands/choco-uninstall.Tests.ps1 index 218db2401c..b12787b52d 100644 --- a/tests/chocolatey-tests/commands/choco-uninstall.Tests.ps1 +++ b/tests/chocolatey-tests/commands/choco-uninstall.Tests.ps1 @@ -1,4 +1,4 @@ -Import-Module helpers/common-helpers +Import-Module helpers/common-helpers Describe "choco uninstall" -Tag Chocolatey, UninstallCommand { BeforeAll { @@ -62,7 +62,7 @@ Describe "choco uninstall" -Tag Chocolatey, UninstallCommand { 'Package Path in Uninstall Script: \lib\test-chocolateypath' 'Install Path in Uninstall Script: ' ) { - $Output.Lines | Should -Contain ($_ -replace '',$env:ChocolateyInstall) -Because $Output.String + $Output.Lines | Should -Contain ($_ -replace '', $env:ChocolateyInstall) -Because $Output.String } } } diff --git a/tests/chocolatey-tests/commands/choco-version.Tests.ps1 b/tests/chocolatey-tests/commands/choco-version.Tests.ps1 index b31734c831..3720baabca 100644 --- a/tests/chocolatey-tests/commands/choco-version.Tests.ps1 +++ b/tests/chocolatey-tests/commands/choco-version.Tests.ps1 @@ -29,7 +29,7 @@ Describe "choco version" -Tag Chocolatey, VersionCommand -Skip:(Test-ChocolateyV } } - Context "Help Documentation (<_>)" -Foreach @("--help", "-?", "-help") { + Context "Help Documentation (<_>)" -ForEach @("--help", "-?", "-help") { BeforeAll { $Output = Invoke-Choco version $_ } diff --git a/tests/chocolatey-tests/commands/testpackages/installpackage/1.0.0/tools/chocolateyinstall.ps1 b/tests/chocolatey-tests/commands/testpackages/installpackage/1.0.0/tools/chocolateyinstall.ps1 index 793673411c..8a3c2cce63 100644 --- a/tests/chocolatey-tests/commands/testpackages/installpackage/1.0.0/tools/chocolateyinstall.ps1 +++ b/tests/chocolatey-tests/commands/testpackages/installpackage/1.0.0/tools/chocolateyinstall.ps1 @@ -1,6 +1,6 @@ -$toolsDir = "$(Split-Path -parent $MyInvocation.MyCommand.Definition)" +$toolsDir = "$(Split-Path -Parent $MyInvocation.MyCommand.Definition)" $PackageParameters = Get-PackageParameters -"simple file" | Out-File "$toolsDir\simplefile.txt" -force +"simple file" | Out-File "$toolsDir\simplefile.txt" -Force Write-Output "This is $packageName v$packageVersion being installed to `n $packageFolder" Write-Host "Ya!" diff --git a/tests/chocolatey-tests/commands/testpackages/zip-log-disable-test/tools/chocolateyinstall.ps1 b/tests/chocolatey-tests/commands/testpackages/zip-log-disable-test/tools/chocolateyinstall.ps1 index cd1f15bd37..35454eb63f 100644 --- a/tests/chocolatey-tests/commands/testpackages/zip-log-disable-test/tools/chocolateyinstall.ps1 +++ b/tests/chocolatey-tests/commands/testpackages/zip-log-disable-test/tools/chocolateyinstall.ps1 @@ -1,12 +1,12 @@ - + $ErrorActionPreference = 'Stop'; -$toolsDir = "$(Split-Path -parent $MyInvocation.MyCommand.Definition)" +$toolsDir = "$(Split-Path -Parent $MyInvocation.MyCommand.Definition)" $packageArgs = @{ - packageName = $env:ChocolateyPackageName - destination = "$toolsDir\extraction" - file = "$toolsDir\zip-log-disable-test.zip" - disableLogging= $true + packageName = $env:ChocolateyPackageName + destination = "$toolsDir\extraction" + file = "$toolsDir\zip-log-disable-test.zip" + disableLogging = $true } Get-ChocolateyUnzip @packageArgs diff --git a/tests/chocolatey-tests/features/PythonSource.Tests.ps1 b/tests/chocolatey-tests/features/PythonSource.Tests.ps1 index f98462719f..ce9eb4a314 100644 --- a/tests/chocolatey-tests/features/PythonSource.Tests.ps1 +++ b/tests/chocolatey-tests/features/PythonSource.Tests.ps1 @@ -14,7 +14,7 @@ Describe "Python Source" -Tag Chocolatey, UpgradeCommand, PythonSource -Skip:(-n Remove-ChocolateyTestInstall } - Context "upgrade " -Foreach @( + Context "upgrade " -ForEach @( @{ Argument = 'all' ; ExitCode = 1 ; Count = 0 } @{ Argument = 'wheel' ; ExitCode = 0 ; Count = 1 } ) -Skip:(-not (Test-ChocolateyVersionEqualOrHigherThan '1.1.0')) { diff --git a/tests/helpers/common/Chocolatey/Get-ChocolateyFeature.ps1 b/tests/helpers/common/Chocolatey/Get-ChocolateyFeature.ps1 index ad91f234bf..ee3afc553d 100644 --- a/tests/helpers/common/Chocolatey/Get-ChocolateyFeature.ps1 +++ b/tests/helpers/common/Chocolatey/Get-ChocolateyFeature.ps1 @@ -15,7 +15,12 @@ $license = Get-ChocolateyLicense # Just so we don't return the actual license for tests # we only specify as true if there is a license. - $isLicensed = if ($license) { $true } else { $false } + $isLicensed = if ($license) { + $true + } + else { + $false + } $is30Licensed = $isLicensed -and (Test-PackageIsEqualOrHigher 'chocolatey.extension' '3.0.0-alpha') $is22Licensed = $isLicensed -and ($is30Licensed -or (Test-PackageIsEqualOrHigher 'chocolatey.extension' '2.2.0-beta')) diff --git a/tests/helpers/common/Chocolatey/Invoke-Choco.ps1 b/tests/helpers/common/Chocolatey/Invoke-Choco.ps1 index 79e136aef1..3427f84183 100644 --- a/tests/helpers/common/Chocolatey/Invoke-Choco.ps1 +++ b/tests/helpers/common/Chocolatey/Invoke-Choco.ps1 @@ -18,7 +18,7 @@ ) begin { $chocoPath = Get-ChocoPath - $firstArgument, [string[]]$remainingArguments = $Arguments + $firstArgument, [string[]]$remainingArguments = $Arguments $arguments = @($firstArgument; '--allow-unofficial'; $remainingArguments) } end { @@ -33,7 +33,12 @@ # We trim all the lines, so we do not take into account # trimming the lines when asserting, and that extra whitespace # is not considered in our assertions. - Lines = if ($output) { $output.Trim() } else { @() } + Lines = if ($output) { + $output.Trim() + } + else { + @() + } String = $output -join "`r`n" ExitCode = $LastExitCode } diff --git a/tests/helpers/common/Chocolatey/Set-ChocolateyFeature.ps1 b/tests/helpers/common/Chocolatey/Set-ChocolateyFeature.ps1 index ffbf57e193..ae597be526 100644 --- a/tests/helpers/common/Chocolatey/Set-ChocolateyFeature.ps1 +++ b/tests/helpers/common/Chocolatey/Set-ChocolateyFeature.ps1 @@ -4,10 +4,10 @@ [Parameter(Mandatory = $true)] [string[]] $Name, - [Parameter(Mandatory = $true, ParameterSetName='Enable')] + [Parameter(Mandatory = $true, ParameterSetName = 'Enable')] [switch] $Enable, - [Parameter(Mandatory = $true, ParameterSetName='Disable')] + [Parameter(Mandatory = $true, ParameterSetName = 'Disable')] [switch] $Disable ) diff --git a/tests/helpers/common/Chocolatey/Test-ChocolateyVersionEqualOrHigherThan.ps1 b/tests/helpers/common/Chocolatey/Test-ChocolateyVersionEqualOrHigherThan.ps1 index c66e4497d6..7233e9506e 100644 --- a/tests/helpers/common/Chocolatey/Test-ChocolateyVersionEqualOrHigherThan.ps1 +++ b/tests/helpers/common/Chocolatey/Test-ChocolateyVersionEqualOrHigherThan.ps1 @@ -10,7 +10,7 @@ param( [NuGet.Versioning.SemanticVersion]$Version ) - $installedVersion = ((Invoke-Choco list -lo -r).Lines | ConvertFrom-ChocolateyOutput -Command List | Where-Object Name -eq 'chocolatey').Version + $installedVersion = ((Invoke-Choco list -lo -r).Lines | ConvertFrom-ChocolateyOutput -Command List | Where-Object Name -EQ 'chocolatey').Version return Test-VersionEqualOrHigher -InstalledVersion $installedVersion -CompareVersion $Version } diff --git a/tests/helpers/common/Get-TempDirectory.ps1 b/tests/helpers/common/Get-TempDirectory.ps1 index e157851aeb..2429ba232e 100644 --- a/tests/helpers/common/Get-TempDirectory.ps1 +++ b/tests/helpers/common/Get-TempDirectory.ps1 @@ -1,7 +1,7 @@ -function Get-TempDirectory { - <# +function Get-TempDirectory { + <# .SYNOPSIS Returns the temporary directory. #> - [System.IO.Path]::GetTempPath() + [System.IO.Path]::GetTempPath() } diff --git a/tests/helpers/common/Logging/Get-ChocoLogData.ps1 b/tests/helpers/common/Logging/Get-ChocoLogData.ps1 index 8a26830ffc..86a06ed8b9 100644 --- a/tests/helpers/common/Logging/Get-ChocoLogData.ps1 +++ b/tests/helpers/common/Logging/Get-ChocoLogData.ps1 @@ -2,7 +2,7 @@ # Strip out the date and other incidental data from the beginning of log lines $chocoLogData = (Get-Content (Get-ChocoLogPath)) -replace '^\d.* \[', '[' [PSCustomObject]@{ - Lines = $chocoLogData + Lines = $chocoLogData String = $chocoLogData -join "`r`n" } } \ No newline at end of file diff --git a/tests/packages/business-only-license/tools/chocolateyinstall.ps1 b/tests/packages/business-only-license/tools/chocolateyinstall.ps1 index fca2255f0e..9308649c43 100755 --- a/tests/packages/business-only-license/tools/chocolateyinstall.ps1 +++ b/tests/packages/business-only-license/tools/chocolateyinstall.ps1 @@ -2,30 +2,30 @@ $LicensedCommandsRegistered = Get-Command "Invoke-ValidateChocolateyLicense" -EA SilentlyContinue if (!$LicensedCommandsRegistered) { - Write-Warning "Package Requires Commercial License - Installation cannot continue as Package Builder use require endpoints to be licensed with Chocolatey Licensed Extension v3.0.0+ (chocolatey.extension). Please see error below for details and correction instructions." - throw "This package requires a commercial edition of Chocolatey as it was built/internalized with commercial features. Please install the license and install/upgrade to Chocolatey Licensed Extension v3.0.0+ as per https://docs.chocolatey.org/en-us/licensed-extension/setup." + Write-Warning "Package Requires Commercial License - Installation cannot continue as Package Builder use require endpoints to be licensed with Chocolatey Licensed Extension v3.0.0+ (chocolatey.extension). Please see error below for details and correction instructions." + throw "This package requires a commercial edition of Chocolatey as it was built/internalized with commercial features. Please install the license and install/upgrade to Chocolatey Licensed Extension v3.0.0+ as per https://docs.chocolatey.org/en-us/licensed-extension/setup." } Invoke-ValidateChocolateyLicense -RequiredLicenseTypes @('Business') -$toolsDir = "$(Split-Path -parent $MyInvocation.MyCommand.Definition)" +$toolsDir = "$(Split-Path -Parent $MyInvocation.MyCommand.Definition)" $fileLocation = Join-Path $toolsDir '7z1900-x64.exe' $packageArgs = @{ - packageName = $env:ChocolateyPackageName - softwareName = '7-Zip*' - file = $fileLocation - fileType = 'exe' - silentArgs = "/S" - - validExitCodes= @(0) - url = "" - checksum = '0F5D4DBBE5E55B7AA31B91E5925ED901FDF46A367491D81381846F05AD54C45E' - checksumType = 'sha256' - url64bit = "" - checksum64 = '' - checksumType64= 'sha256' - destination = $toolsDir + packageName = $env:ChocolateyPackageName + softwareName = '7-Zip*' + file = $fileLocation + fileType = 'exe' + silentArgs = "/S" + + validExitCodes = @(0) + url = "" + checksum = '0F5D4DBBE5E55B7AA31B91E5925ED901FDF46A367491D81381846F05AD54C45E' + checksumType = 'sha256' + url64bit = "" + checksum64 = '' + checksumType64 = 'sha256' + destination = $toolsDir } Install-ChocolateyInstallPackage @packageArgs diff --git a/tests/packages/business-only-license/tools/chocolateyuninstall.ps1 b/tests/packages/business-only-license/tools/chocolateyuninstall.ps1 index 0260fea52b..59603598d4 100755 --- a/tests/packages/business-only-license/tools/chocolateyuninstall.ps1 +++ b/tests/packages/business-only-license/tools/chocolateyuninstall.ps1 @@ -1,26 +1,28 @@ $ErrorActionPreference = 'Stop' $packageArgs = @{ - packageName = $env:ChocolateyPackageName - softwareName = '7-Zip*' - fileType = 'exe' - silentArgs = "/S" - validExitCodes= @(0) + packageName = $env:ChocolateyPackageName + softwareName = '7-Zip*' + fileType = 'exe' + silentArgs = "/S" + validExitCodes = @(0) } [array]$key = Get-UninstallRegistryKey -SoftwareName $packageArgs['softwareName'] if ($key.Count -eq 1) { - $key | % { - $packageArgs['file'] = "$($_.UninstallString)" + $key | ForEach-Object { + $packageArgs['file'] = "$($_.UninstallString)" - Uninstall-ChocolateyPackage @packageArgs - } -} elseif ($key.Count -eq 0) { - Write-Warning "$env:ChocolateyPackageName has already been uninstalled by other means." -} elseif ($key.Count -gt 1) { - Write-Warning "$($key.Count) matches found!" - Write-Warning "To prevent accidental data loss, no programs will be uninstalled." - Write-Warning "Please alert package maintainer the following keys were matched:" - $key | % {Write-Warning "- $($_.DisplayName)"} + Uninstall-ChocolateyPackage @packageArgs + } +} +elseif ($key.Count -eq 0) { + Write-Warning "$env:ChocolateyPackageName has already been uninstalled by other means." +} +elseif ($key.Count -gt 1) { + Write-Warning "$($key.Count) matches found!" + Write-Warning "To prevent accidental data loss, no programs will be uninstalled." + Write-Warning "Please alert package maintainer the following keys were matched:" + $key | ForEach-Object { Write-Warning "- $($_.DisplayName)" } } diff --git a/tests/packages/get-chocolateyunzip-custom-paths/0.0.1/tools/chocolateyinstall.ps1 b/tests/packages/get-chocolateyunzip-custom-paths/0.0.1/tools/chocolateyinstall.ps1 index 57adf85c28..44ac9aafd7 100644 --- a/tests/packages/get-chocolateyunzip-custom-paths/0.0.1/tools/chocolateyinstall.ps1 +++ b/tests/packages/get-chocolateyunzip-custom-paths/0.0.1/tools/chocolateyinstall.ps1 @@ -1,10 +1,11 @@ -$toolsDir = "$(Split-Path -parent $MyInvocation.MyCommand.Definition)" +$toolsDir = "$(Split-Path -Parent $MyInvocation.MyCommand.Definition)" $zipFileLocation = Join-Path $toolsDir "test.zip" $pp = Get-PackageParameters if ($pp['Destination']) { - $destinationPath = $pp['Destination'] -} else { - $destinationPath = $env:TEMP + $destinationPath = $pp['Destination'] +} +else { + $destinationPath = $env:TEMP } -Get-ChocolateyUnzip -FileFullPath $zipFileLocation -Destination $destinationPath +Get-ChocolateyUnzip -fileFullPath $zipFileLocation -destination $destinationPath diff --git a/tests/packages/get-chocolateyunzip-licensed/tools/chocolateyinstall.ps1 b/tests/packages/get-chocolateyunzip-licensed/tools/chocolateyinstall.ps1 index e10b6bb76e..b2f2878230 100755 --- a/tests/packages/get-chocolateyunzip-licensed/tools/chocolateyinstall.ps1 +++ b/tests/packages/get-chocolateyunzip-licensed/tools/chocolateyinstall.ps1 @@ -1,46 +1,47 @@ $ErrorActionPreference = 'Stop' -$toolsDir = "$(Split-Path -parent $MyInvocation.MyCommand.Definition)" +$toolsDir = "$(Split-Path -Parent $MyInvocation.MyCommand.Definition)" $fileLocation = Join-Path $toolsDir 'cmake-3.21.2-windows-i386.zip' $fileLocation64 = Join-Path $toolsDir 'cmake-3.21.2-windows-x86_64.zip' if (Get-ProcessorBits 64) { -$forceX86 = $env:chocolateyForceX86 - if ($forceX86 -eq 'true') { - Write-Debug "User specified '-x86' so forcing 32-bit" - } else { - $fileLocation = $fileLocation64 - } + $forceX86 = $env:chocolateyForceX86 + if ($forceX86 -eq 'true') { + Write-Debug "User specified '-x86' so forcing 32-bit" + } + else { + $fileLocation = $fileLocation64 + } } #Based on Custom $packageArgs = @{ - packageName = $env:ChocolateyPackageName - softwareName = 'get-chocolateyunzip-licensed*' - file = $fileLocation - fileType = 'zip' - silentArgs = "" - #OTHERS - # Uncomment matching EXE type (sorted by most to least common) - #$silentArgs = '/S' # NSIS - #silentArgs = '/VERYSILENT /SUPPRESSMSGBOXES /NORESTART /SP-' # Inno Setup - #silentArgs = '/s' # InstallShield - #silentArgs = '/s /v"/qn"' # InstallShield with MSI - #silentArgs = '/s' # Wise InstallMaster - #silentArgs = '-s' # Squirrel - #silentArgs = '-q' # Install4j - #silentArgs = '-s' # Ghost - # Note that some installers, in addition to the silentArgs above, may also need assistance of AHK to achieve silence. - #silentArgs = '' # none; make silent with input macro script like AutoHotKey (AHK) - # https://chocolatey.org/packages/autohotkey.portable - - validExitCodes= @(0) - url = "" - checksum = '9374249E8CA5CFE899F6A8DC95252E79242290E452B3CE12A88449560143B6E9' - checksumType = 'sha256' - url64bit = "" - checksum64 = '213A4E6485B711CB0A48CBD97B10DFE161A46BFE37B8F3205F47E99FFEC434D2' - checksumType64= 'sha256' - destination = $toolsDir + packageName = $env:ChocolateyPackageName + softwareName = 'get-chocolateyunzip-licensed*' + file = $fileLocation + fileType = 'zip' + silentArgs = "" + #OTHERS + # Uncomment matching EXE type (sorted by most to least common) + #$silentArgs = '/S' # NSIS + #silentArgs = '/VERYSILENT /SUPPRESSMSGBOXES /NORESTART /SP-' # Inno Setup + #silentArgs = '/s' # InstallShield + #silentArgs = '/s /v"/qn"' # InstallShield with MSI + #silentArgs = '/s' # Wise InstallMaster + #silentArgs = '-s' # Squirrel + #silentArgs = '-q' # Install4j + #silentArgs = '-s' # Ghost + # Note that some installers, in addition to the silentArgs above, may also need assistance of AHK to achieve silence. + #silentArgs = '' # none; make silent with input macro script like AutoHotKey (AHK) + # https://chocolatey.org/packages/autohotkey.portable + + validExitCodes = @(0) + url = "" + checksum = '9374249E8CA5CFE899F6A8DC95252E79242290E452B3CE12A88449560143B6E9' + checksumType = 'sha256' + url64bit = "" + checksum64 = '213A4E6485B711CB0A48CBD97B10DFE161A46BFE37B8F3205F47E99FFEC434D2' + checksumType64 = 'sha256' + destination = $toolsDir } Get-ChocolateyUnzipCmdlet @packageArgs diff --git a/tests/packages/get-chocolateyunzip-test/0.0.1/tools/chocolateyinstall.ps1 b/tests/packages/get-chocolateyunzip-test/0.0.1/tools/chocolateyinstall.ps1 index 8b09d934c8..251c43f30c 100644 --- a/tests/packages/get-chocolateyunzip-test/0.0.1/tools/chocolateyinstall.ps1 +++ b/tests/packages/get-chocolateyunzip-test/0.0.1/tools/chocolateyinstall.ps1 @@ -1,17 +1,15 @@ -$toolsDir = "$(Split-Path -parent $MyInvocation.MyCommand.Definition)" +$toolsDir = "$(Split-Path -Parent $MyInvocation.MyCommand.Definition)" $zipFileLocation = Join-Path $toolsDir "test.zip" -if ((Get-Location) -eq $null) -{ - Write-Warning "Working Directory not set. Setting to '$env:ChocolateyInstall'" - Set-Location $env:ChocolateyInstall #See https://github.com/chocolatey/choco/issues/1781 +if ((Get-Location) -eq $null) { + Write-Warning "Working Directory not set. Setting to '$env:ChocolateyInstall'" + Set-Location $env:ChocolateyInstall #See https://github.com/chocolatey/choco/issues/1781 } -if ([string]::IsNullOrEmpty((Get-Location))) -{ - Write-Warning "Working Directory is an empty string. Setting to '$env:ChocolateyInstall'" - Set-Location $env:ChocolateyInstall #See https://github.com/chocolatey/choco/issues/1781 +if ([string]::IsNullOrEmpty((Get-Location))) { + Write-Warning "Working Directory is an empty string. Setting to '$env:ChocolateyInstall'" + Set-Location $env:ChocolateyInstall #See https://github.com/chocolatey/choco/issues/1781 } Write-Debug "Working Directory is now '$(Get-Location)'" -Get-ChocolateyUnzip -FileFullPath $zipFileLocation -Destination $toolsDir +Get-ChocolateyUnzip -fileFullPath $zipFileLocation -destination $toolsDir diff --git a/tests/packages/get-chocolateyunzip-test/0.0.2/tools/chocolateyinstall.ps1 b/tests/packages/get-chocolateyunzip-test/0.0.2/tools/chocolateyinstall.ps1 index 60b8b650b0..452f2231d2 100644 --- a/tests/packages/get-chocolateyunzip-test/0.0.2/tools/chocolateyinstall.ps1 +++ b/tests/packages/get-chocolateyunzip-test/0.0.2/tools/chocolateyinstall.ps1 @@ -1,15 +1,15 @@ -$toolsDir = "$(Split-Path -parent $MyInvocation.MyCommand.Definition)" +$toolsDir = "$(Split-Path -Parent $MyInvocation.MyCommand.Definition)" $zipFileLocation = Join-Path $toolsDir "test.zip" if ((Get-Location) -eq $null) { - Write-Warning "Working Directory not set. Setting to '$env:ChocolateyInstall'" - Set-Location $env:ChocolateyInstall #See https://github.com/chocolatey/choco/issues/1781 + Write-Warning "Working Directory not set. Setting to '$env:ChocolateyInstall'" + Set-Location $env:ChocolateyInstall #See https://github.com/chocolatey/choco/issues/1781 } if ([string]::IsNullOrEmpty((Get-Location))) { - Write-Warning "Working Directory is an empty string. Setting to '$env:ChocolateyInstall'" - Set-Location $env:ChocolateyInstall #See https://github.com/chocolatey/choco/issues/1781 + Write-Warning "Working Directory is an empty string. Setting to '$env:ChocolateyInstall'" + Set-Location $env:ChocolateyInstall #See https://github.com/chocolatey/choco/issues/1781 } Write-Debug "Working Directory is now '$(Get-Location)'" -Get-ChocolateyUnzip -FileFullPath $zipFileLocation -UnzipLocation $toolsDir +Get-ChocolateyUnzip -fileFullPath $zipFileLocation -UnzipLocation $toolsDir diff --git a/tests/packages/hasbeforeinstallblock/1.0.0/tools/chocolateyinstall.ps1 b/tests/packages/hasbeforeinstallblock/1.0.0/tools/chocolateyinstall.ps1 index a7cda6409c..1357a224bc 100644 --- a/tests/packages/hasbeforeinstallblock/1.0.0/tools/chocolateyinstall.ps1 +++ b/tests/packages/hasbeforeinstallblock/1.0.0/tools/chocolateyinstall.ps1 @@ -1,57 +1,59 @@ $ErrorActionPreference = 'Stop' # stop on all errors $packageArgs = @{ - packageName = $env:ChocolateyPackageName - fileType = 'msi' - url = 'https://github.com/chocolatey/ChocolateyGUI/releases/download/0.18.1/ChocolateyGUI.msi' + packageName = $env:ChocolateyPackageName + fileType = 'msi' + url = 'https://github.com/chocolatey/ChocolateyGUI/releases/download/0.18.1/ChocolateyGUI.msi' - softwareName = 'Chocolatey GUI*' + softwareName = 'Chocolatey GUI*' - checksum = '' - checksumType = 'sha256' + checksum = '' + checksumType = 'sha256' - # MSI - silentArgs = "/qn /norestart /l*v `"$($env:TEMP)\$($packageName).$($env:chocolateyPackageVersion).MsiInstall.log`"" # ALLUSERS=1 DISABLEDESKTOPSHORTCUT=1 ADDDESKTOPICON=0 ADDSTARTMENU=0 - validExitCodes= @(0, 3010, 1641) + # MSI + silentArgs = "/qn /norestart /l*v `"$($env:TEMP)\$($packageName).$($env:chocolateyPackageVersion).MsiInstall.log`"" # ALLUSERS=1 DISABLEDESKTOPSHORTCUT=1 ADDDESKTOPICON=0 ADDSTARTMENU=0 + validExitCodes = @(0, 3010, 1641) - beforeInstall = { - # This is just to notify that the before install script - # block have been ran - Write-Host "Running necessary Pre-Install step" - } + beforeInstall = { + # This is just to notify that the before install script + # block have been ran + Write-Host "Running necessary Pre-Install step" + } } $pp = Get-PackageParameters $algorithms = @{ - "MD5" = "27272275D1851F8E68C02BCE79538E2A" - "SHA1" = "2D8214F84162069FB809776287DBB5BCAA5AE725" - "SHA256" = "490DCAC8A2BF52CB55A84686EEB2D23A4B303578AE09A0290D3208AEFBE5B59D" - "SHA512" = "D8FB6BE60863D145CEE1CF12AEA66C6E5042CE0C04DB6FABF4C2659EEE87C63E6830514945C56B059B76311C02CC6AFD64BC73FF3AF0B4EE993CCA4545BF0FD3" + "MD5" = "27272275D1851F8E68C02BCE79538E2A" + "SHA1" = "2D8214F84162069FB809776287DBB5BCAA5AE725" + "SHA256" = "490DCAC8A2BF52CB55A84686EEB2D23A4B303578AE09A0290D3208AEFBE5B59D" + "SHA512" = "D8FB6BE60863D145CEE1CF12AEA66C6E5042CE0C04DB6FABF4C2659EEE87C63E6830514945C56B059B76311C02CC6AFD64BC73FF3AF0B4EE993CCA4545BF0FD3" } if ($pp.Algorithm) { - if ($pp.Algorithm -eq $true) { - # This allows us to test when the checksum type is specified - # but is set to empty - $packageArgs["checksumType"] = "" - $packageArgs["checksum"] = $algorithms["MD5"] # Default is MD5 when type is not specified, or is empty - } - else { - $packageArgs["checksumType"] = $pp.Algorithm - $packageArgs["checksum"] = $algorithms[$pp.Algorithm] - } -} else { - $packageArgs["checksum"] = $algorithms["SHA256"] + if ($pp.Algorithm -eq $true) { + # This allows us to test when the checksum type is specified + # but is set to empty + $packageArgs["checksumType"] = "" + $packageArgs["checksum"] = $algorithms["MD5"] # Default is MD5 when type is not specified, or is empty + } + else { + $packageArgs["checksumType"] = $pp.Algorithm + $packageArgs["checksum"] = $algorithms[$pp.Algorithm] + } +} +else { + $packageArgs["checksum"] = $algorithms["SHA256"] } if ($pp.Checksum) { - if ($pp.Checksum -eq $true) { - # This allows us to test when there is an empty checksum - $packageArgs["checksum"] = "" - } else { - $packageArgs["checksum"] = $pp.Checksum - } + if ($pp.Checksum -eq $true) { + # This allows us to test when there is an empty checksum + $packageArgs["checksum"] = "" + } + else { + $packageArgs["checksum"] = $pp.Checksum + } } Write-Host "Using Algorithm: $($packageArgs["checksumType"])" diff --git a/tests/packages/msi.template/templates/tools/chocolateybeforemodify.ps1 b/tests/packages/msi.template/templates/tools/chocolateybeforemodify.ps1 index 9588ffe803..2e50a2b2f4 100644 --- a/tests/packages/msi.template/templates/tools/chocolateybeforemodify.ps1 +++ b/tests/packages/msi.template/templates/tools/chocolateybeforemodify.ps1 @@ -4,6 +4,6 @@ # need to uninstall an MSI prior to upgrade, put the functionality in this # file without calling the uninstall script. Make it idempotent in the # uninstall script so that it doesn't fail when it is already uninstalled. -# NOTE: For upgrades - like the uninstall script, this script always runs from +# NOTE: For upgrades - like the uninstall script, this script always runs from # the currently installed version, not from the new upgraded package version. diff --git a/tests/packages/msi.template/templates/tools/chocolateyinstall.ps1 b/tests/packages/msi.template/templates/tools/chocolateyinstall.ps1 index 1a7f6a7372..0ed9d1e168 100644 --- a/tests/packages/msi.template/templates/tools/chocolateyinstall.ps1 +++ b/tests/packages/msi.template/templates/tools/chocolateyinstall.ps1 @@ -1,27 +1,27 @@ $ErrorActionPreference = 'Stop' [[AutomaticPackageNotesInstaller]] -$packageName= '[[PackageName]]' -$toolsDir = "$(Split-Path -parent $MyInvocation.MyCommand.Definition)" +$packageName = '[[PackageName]]' +$toolsDir = "$(Split-Path -Parent $MyInvocation.MyCommand.Definition)" #$fileLocation = Join-Path $toolsDir 'NAME_OF_EMBEDDED_INSTALLER_FILE' $packageArgs = @{ - packageName = $packageName - unzipLocation = $toolsDir - fileType = 'MSI' - url = '[[Url]]' # download url, HTTPS preferred - url64bit = '[[Url64]]' # 64bit URL here (HTTPS preferred) or remove - if installer contains both (very rare), use $url - #file = $fileLocation + packageName = $packageName + unzipLocation = $toolsDir + fileType = 'MSI' + url = '[[Url]]' # download url, HTTPS preferred + url64bit = '[[Url64]]' # 64bit URL here (HTTPS preferred) or remove - if installer contains both (very rare), use $url + #file = $fileLocation - softwareName = '[[PackageName]]*' #part or all of the Display Name as you see it in Programs and Features. It should be enough to be unique + softwareName = '[[PackageName]]*' #part or all of the Display Name as you see it in Programs and Features. It should be enough to be unique - checksum = '[[Checksum]]' - checksumType = 'sha256' #default is md5, can also be sha1, sha256 or sha512 - checksum64 = '[[Checksum64]]' - checksumType64= 'sha256' + checksum = '[[Checksum]]' + checksumType = 'sha256' #default is md5, can also be sha1, sha256 or sha512 + checksum64 = '[[Checksum64]]' + checksumType64 = 'sha256' - silentArgs = "[[SilentArgs]]" # ALLUSERS=1 DISABLEDESKTOPSHORTCUT=1 ADDDESKTOPICON=0 ADDSTARTMENU=0 - validExitCodes= @(0, 3010, 1641) + silentArgs = "[[SilentArgs]]" # ALLUSERS=1 DISABLEDESKTOPSHORTCUT=1 ADDDESKTOPICON=0 ADDSTARTMENU=0 + validExitCodes = @(0, 3010, 1641) } #https://chocolatey.org/docs/helpers-install-chocolatey-package diff --git a/tests/packages/msi.template/templates/tools/chocolateyuninstall.ps1 b/tests/packages/msi.template/templates/tools/chocolateyuninstall.ps1 index 63b9c4781f..00fd5de92d 100644 --- a/tests/packages/msi.template/templates/tools/chocolateyuninstall.ps1 +++ b/tests/packages/msi.template/templates/tools/chocolateyuninstall.ps1 @@ -16,32 +16,34 @@ $uninstalled = $false [array]$key = Get-UninstallRegistryKey -SoftwareName $softwareName if ($key.Count -eq 1) { - $key | ForEach-Object { - $file = "$($_.UninstallString)" + $key | ForEach-Object { + $file = "$($_.UninstallString)" - if ($installerType -eq 'MSI') { - # The Product Code GUID is all that should be passed for MSI, and very - # FIRST, because it comes directly after /x, which is already set in the - # Uninstall-ChocolateyPackage msiargs (facepalm). - $silentArgs = "$($_.PSChildName) $silentArgs" + if ($installerType -eq 'MSI') { + # The Product Code GUID is all that should be passed for MSI, and very + # FIRST, because it comes directly after /x, which is already set in the + # Uninstall-ChocolateyPackage msiargs (facepalm). + $silentArgs = "$($_.PSChildName) $silentArgs" - # Don't pass anything for file, it is ignored for msi (facepalm number 2) - # Alternatively if you need to pass a path to an msi, determine that and - # use it instead of the above in silentArgs, still very first - $file = '' - } + # Don't pass anything for file, it is ignored for msi (facepalm number 2) + # Alternatively if you need to pass a path to an msi, determine that and + # use it instead of the above in silentArgs, still very first + $file = '' + } - Uninstall-ChocolateyPackage -PackageName $packageName ` - -FileType $installerType ` - -SilentArgs "$silentArgs" ` - -ValidExitCodes $validExitCodes ` - -File "$file" - } -} elseif ($key.Count -eq 0) { - Write-Warning "$packageName has already been uninstalled by other means." -} elseif ($key.Count -gt 1) { - Write-Warning "$key.Count matches found!" - Write-Warning "To prevent accidental data loss, no programs will be uninstalled." - Write-Warning "Please alert package maintainer the following keys were matched:" - $key | ForEach-Object {Write-Warning "- $_.DisplayName"} + Uninstall-ChocolateyPackage -packageName $packageName ` + -fileType $installerType ` + -silentArgs "$silentArgs" ` + -validExitCodes $validExitCodes ` + -file "$file" + } +} +elseif ($key.Count -eq 0) { + Write-Warning "$packageName has already been uninstalled by other means." +} +elseif ($key.Count -gt 1) { + Write-Warning "$key.Count matches found!" + Write-Warning "To prevent accidental data loss, no programs will be uninstalled." + Write-Warning "Please alert package maintainer the following keys were matched:" + $key | ForEach-Object { Write-Warning "- $_.DisplayName" } } \ No newline at end of file diff --git a/tests/packages/test-chocolateypath/tools/chocolateybeforemodify.ps1 b/tests/packages/test-chocolateypath/tools/chocolateybeforemodify.ps1 index aed0c325fb..dcacd6b2ce 100644 --- a/tests/packages/test-chocolateypath/tools/chocolateybeforemodify.ps1 +++ b/tests/packages/test-chocolateypath/tools/chocolateybeforemodify.ps1 @@ -1,7 +1,7 @@ $ErrorActionPreference = 'Stop' -$packagePath = Get-ChocolateyPath -PathType 'PackagePath' -$installPath = Get-ChocolateyPath -PathType 'InstallPath' +$packagePath = Get-ChocolateyPath -pathType 'PackagePath' +$installPath = Get-ChocolateyPath -pathType 'InstallPath' Write-Host "Package Path in Before Modify Script: $packagePath" Write-Host "Install Path in Before Modify Script: $installPath" \ No newline at end of file diff --git a/tests/packages/test-chocolateypath/tools/chocolateyinstall.ps1 b/tests/packages/test-chocolateypath/tools/chocolateyinstall.ps1 index 7d3dd5c585..06d378a569 100644 --- a/tests/packages/test-chocolateypath/tools/chocolateyinstall.ps1 +++ b/tests/packages/test-chocolateypath/tools/chocolateyinstall.ps1 @@ -1,7 +1,7 @@ $ErrorActionPreference = 'Stop' -$packagePath = Get-ChocolateyPath -PathType 'PackagePath' -$installPath = Get-ChocolateyPath -PathType 'InstallPath' +$packagePath = Get-ChocolateyPath -pathType 'PackagePath' +$installPath = Get-ChocolateyPath -pathType 'InstallPath' Write-Host "Package Path in Install Script: $packagePath" Write-Host "Install Path in Install Script: $installPath" \ No newline at end of file diff --git a/tests/packages/test-chocolateypath/tools/chocolateyuninstall.ps1 b/tests/packages/test-chocolateypath/tools/chocolateyuninstall.ps1 index afc17122df..3181dd8b0e 100644 --- a/tests/packages/test-chocolateypath/tools/chocolateyuninstall.ps1 +++ b/tests/packages/test-chocolateypath/tools/chocolateyuninstall.ps1 @@ -1,7 +1,7 @@ $ErrorActionPreference = 'Stop' -$packagePath = Get-ChocolateyPath -PathType 'PackagePath' -$installPath = Get-ChocolateyPath -PathType 'InstallPath' +$packagePath = Get-ChocolateyPath -pathType 'PackagePath' +$installPath = Get-ChocolateyPath -pathType 'InstallPath' Write-Host "Package Path in Uninstall Script: $packagePath" Write-Host "Install Path in Uninstall Script: $installPath" \ No newline at end of file diff --git a/tests/packages/zip.template/templates/tools/chocolateybeforemodify.ps1 b/tests/packages/zip.template/templates/tools/chocolateybeforemodify.ps1 index 9588ffe803..2e50a2b2f4 100644 --- a/tests/packages/zip.template/templates/tools/chocolateybeforemodify.ps1 +++ b/tests/packages/zip.template/templates/tools/chocolateybeforemodify.ps1 @@ -4,6 +4,6 @@ # need to uninstall an MSI prior to upgrade, put the functionality in this # file without calling the uninstall script. Make it idempotent in the # uninstall script so that it doesn't fail when it is already uninstalled. -# NOTE: For upgrades - like the uninstall script, this script always runs from +# NOTE: For upgrades - like the uninstall script, this script always runs from # the currently installed version, not from the new upgraded package version. diff --git a/tests/packages/zip.template/templates/tools/chocolateyinstall.ps1 b/tests/packages/zip.template/templates/tools/chocolateyinstall.ps1 index fc18b68e4a..910aa704b3 100644 --- a/tests/packages/zip.template/templates/tools/chocolateyinstall.ps1 +++ b/tests/packages/zip.template/templates/tools/chocolateyinstall.ps1 @@ -1,23 +1,23 @@ $ErrorActionPreference = 'Stop' [[AutomaticPackageNotesInstaller]] -$packageName= '[[PackageName]]' -$toolsDir = "$(Split-Path -parent $MyInvocation.MyCommand.Definition)" +$packageName = '[[PackageName]]' +$toolsDir = "$(Split-Path -Parent $MyInvocation.MyCommand.Definition)" #$fileLocation = Join-Path $toolsDir 'NAME_OF_EMBEDDED_ZIP_FILE' $packageArgs = @{ - packageName = $packageName - unzipLocation = $toolsDir - url = '[[Url]]' # download url, HTTPS preferred - url64bit = '[[Url64]]' # 64bit URL here (HTTPS preferred) or remove - if installer contains both (very rare), use $url - #file = $fileLocation - #fileFullPath = $fileLocation - destination = $toolsDir + packageName = $packageName + unzipLocation = $toolsDir + url = '[[Url]]' # download url, HTTPS preferred + url64bit = '[[Url64]]' # 64bit URL here (HTTPS preferred) or remove - if installer contains both (very rare), use $url + #file = $fileLocation + #fileFullPath = $fileLocation + destination = $toolsDir - checksum = '[[Checksum]]' - checksumType = 'sha256' #default is md5, can also be sha1, sha256 or sha512 - checksum64 = '[[Checksum64]]' - checksumType64= 'sha256' + checksum = '[[Checksum]]' + checksumType = 'sha256' #default is md5, can also be sha1, sha256 or sha512 + checksum64 = '[[Checksum64]]' + checksumType64 = 'sha256' } # https://chocolatey.org/docs/helpers-install-chocolatey-zip-package