1 Chocolatey 的安装

在国内这个工具不好安装,经常由于超时,不能成功。

前面两种方法是推荐的,但是不好用。最好使用第三种,即离线安装的方法。

安装的系统要求

(1) Windows 7+ / Windows Server 2003+
(2) PowerShell v2+,至少是 v3
(3) NET Framework 4+ 至少是 4.5 (安装过程中会自动检测并下载)

1.1 cmd

Win+R 打开运行框,输入 cmd 后,按下 Ctrl+Shift+Enter 进入管理员模式,输入以下命令:

@"%SystemRoot%\System32\WindowsPowerShell\v1.0\powershell.exe" -NoProfile -InputFormat None -ExecutionPolicy Bypass -Command "iex ((New-Object System.Net.WebClient).DownloadString('https://chocolatey.org/install.ps1'))" && SET "PATH=%PATH%;%ALLUSERSPROFILE%\chocolatey\bin"

1.2 Windows PowerShell

Win+R 打开运行框,输入 powershell 后,按下 Ctrl+Shift+Enter 进入管理员模式,输入以下命令:

Set-ExecutionPolicy Bypass -Scope Process -Force; [System.Net.ServicePointManager]::SecurityProtocol = [System.Net.ServicePointManager]::SecurityProtocol -bor 3072; iex ((New-Object System.Net.WebClient).DownloadString('https://community.chocolatey.org/install.ps1'))

1.3 离线安装的方法,比较靠谱

问题描述:安装choco的时候,总是超时失败。

1.3.1 前置条件,下载必须的nupkg

https://packages.chocolatey.org/chocolatey.0.10.15.nupkg

下载chocolatey.0.10.15.nupkg,和最下面的install.ps1脚本放在同一目录。

1.3.2 离线安装choco

参考: https://blog.csdn.net/sw3114/article/details/104299003

choco官方离线安装方案: https://docs.chocolatey.org/en-us/choco/setup

修改install.ps1脚本中的几行:

# 修改第46行的nupkg包路径
$localChocolateyPackageFilePath = 'nupkg包路径'


修改第277行:

# 第277行 Download-Package 这个注释掉
Download-Package $searchUrl $localChocolateyPackageFilePath

install.ps1脚本

install.ps1内容放在最后面,将该脚本保存到本地,和chocolatey.0.10.15.nupkg文件放在同一目录。

powersell开启信任脚本策略

# 开启信任脚本策略
set-ExecutionPolicy RemoteSigned

以管理员powershell执行安装脚本

# 进入脚本所在目录
cd D:\Choco脚本所在目录# 执行安装脚本
iex ./install.ps1

结果验证

# 查看choco版本
choco -v

2 Chocolatey 的使用

# 查看版本
choco -v# 查找软件
choco search XXX# 详细信息
# choco info XXX# 升级软件
choco upgrade XXX# 卸载软件
choco uninstall XXX# 列出包
choco list -lo# 查看本地安装的软件包
choco list --local-only# 配置统一环境 [XXX为配置文件名]
choco install XXX.config# 列出Windows系统已安装的软件
choco list -li  OR choco list -lai

install.psl 代码

# Download and install Chocolatey nupkg from an OData (HTTP/HTTPS) url such as Artifactory, Nexus, ProGet (all of these are recommended for organizational use), or Chocolatey.Server (great for smaller organizations and POCs)
# This is where you see the top level API - with xml to Packages - should look nearly the same as https://chocolatey.org/api/v2/
# If you are using Nexus, always add the trailing slash or it won't work
# === EDIT HERE ===
$packageRepo = '<INSERT ODATA REPO URL>'# If the above $packageRepo repository requires authentication, add the username and password here. Otherwise these leave these as empty strings.
$repoUsername = ''    # this must be empty is NOT using authentication
$repoPassword = ''    # this must be empty if NOT using authentication# Determine unzipping method
# 7zip is the most compatible, but you need an internally hosted 7za.exe.
# Make sure the version matches for the arguments as well.
# Built-in does not work with Server Core, but if you have PowerShell 5
# it uses Expand-Archive instead of COM
$unzipMethod = 'builtin'
#$unzipMethod = '7zip'
#$7zipUrl = 'https://chocolatey.org/7za.exe' (download this file, host internally, and update this to internal)# === ENVIRONMENT VARIABLES YOU CAN SET ===
# Prior to running this script, in a PowerShell session, you can set the
# following environment variables and it will affect the output# - $env:ChocolateyEnvironmentDebug = 'true' # see output
# - $env:chocolateyIgnoreProxy = 'true' # ignore proxy
# - $env:chocolateyProxyLocation = '' # explicit proxy
# - $env:chocolateyProxyUser = '' # explicit proxy user name (optional)
# - $env:chocolateyProxyPassword = '' # explicit proxy password (optional)# === NO NEED TO EDIT ANYTHING BELOW THIS LINE ===
# Ensure we can run everything
Set-ExecutionPolicy Bypass -Scope Process -Force;# If the repository requires authentication, create the Credential object
if ((-not [string]::IsNullOrEmpty($repoUsername)) -and (-not [string]::IsNullOrEmpty($repoPassword))) {$securePassword = ConvertTo-SecureString $repoPassword -AsPlainText -Force$repoCreds = New-Object System.Management.Automation.PSCredential ($repoUsername, $securePassword)
}$searchUrl = ($packageRepo.Trim('/'), 'Packages()?$filter=(Id%20eq%20%27chocolatey%27)%20and%20IsLatestVersion') -join '/'# Reroute TEMP to a local location
New-Item $env:ALLUSERSPROFILE\choco-cache -ItemType Directory -Force
$env:TEMP = "$env:ALLUSERSPROFILE\choco-cache"
# 46行的变量值携程nupkg的路径,用单引号括起来
$localChocolateyPackageFilePath = 'E:\Downloads\choco\chocolatey.0.10.15.nupkg'
$ChocoInstallPath = "$($env:SystemDrive)\ProgramData\Chocolatey\bin"
$env:ChocolateyInstall = "$($env:SystemDrive)\ProgramData\Chocolatey"
$env:Path += ";$ChocoInstallPath"
$DebugPreference = 'Continue';# PowerShell v2/3 caches the output stream. Then it throws errors due
# to the FileStream not being what is expected. Fixes "The OS handle's
# position is not what FileStream expected. Do not use a handle
# simultaneously in one FileStream and in Win32 code or another
# FileStream."
function Fix-PowerShellOutputRedirectionBug {$poshMajorVerion = $PSVersionTable.PSVersion.Majorif ($poshMajorVerion -lt 4) {try{# http://www.leeholmes.com/blog/2008/07/30/workaround-the-os-handles-position-is-not-what-filestream-expected/ plus comments$bindingFlags = [Reflection.BindingFlags] "Instance,NonPublic,GetField"$objectRef = $host.GetType().GetField("externalHostRef", $bindingFlags).GetValue($host)$bindingFlags = [Reflection.BindingFlags] "Instance,NonPublic,GetProperty"$consoleHost = $objectRef.GetType().GetProperty("Value", $bindingFlags).GetValue($objectRef, @())[void] $consoleHost.GetType().GetProperty("IsStandardOutputRedirected", $bindingFlags).GetValue($consoleHost, @())$bindingFlags = [Reflection.BindingFlags] "Instance,NonPublic,GetField"$field = $consoleHost.GetType().GetField("standardOutputWriter", $bindingFlags)$field.SetValue($consoleHost, [Console]::Out)[void] $consoleHost.GetType().GetProperty("IsStandardErrorRedirected", $bindingFlags).GetValue($consoleHost, @())$field2 = $consoleHost.GetType().GetField("standardErrorWriter", $bindingFlags)$field2.SetValue($consoleHost, [Console]::Error)} catch {Write-Output 'Unable to apply redirection fix.'}}
}Fix-PowerShellOutputRedirectionBug# Attempt to set highest encryption available for SecurityProtocol.
# 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 {# 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 -bor 48
} 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+.'
}function Get-Downloader {param ([string]$url)$downloader = new-object System.Net.WebClient$defaultCreds = [System.Net.CredentialCache]::DefaultCredentialsif (Test-Path -Path variable:repoCreds) {Write-Debug "Using provided repository authentication credentials."$downloader.Credentials = $repoCreds} elseif ($defaultCreds -ne $null) {Write-Debug "Using default repository authentication credentials."$downloader.Credentials = $defaultCreds}$ignoreProxy = $env:chocolateyIgnoreProxyif ($ignoreProxy -ne $null -and $ignoreProxy -eq 'true') {Write-Debug 'Explicitly bypassing proxy due to user environment variable.'$downloader.Proxy = [System.Net.GlobalProxySelection]::GetEmptyWebProxy()} else {# check if a proxy is required$explicitProxy = $env:chocolateyProxyLocation$explicitProxyUser = $env:chocolateyProxyUser$explicitProxyPassword = $env:chocolateyProxyPasswordif ($explicitProxy -ne $null -and $explicitProxy -ne '') {# explicit proxy$proxy = New-Object System.Net.WebProxy($explicitProxy, $true)if ($explicitProxyPassword -ne $null -and $explicitProxyPassword -ne '') {$passwd = ConvertTo-SecureString $explicitProxyPassword -AsPlainText -Force$proxy.Credentials = New-Object System.Management.Automation.PSCredential ($explicitProxyUser, $passwd)}Write-Debug "Using explicit proxy server '$explicitProxy'."$downloader.Proxy = $proxy} elseif (!$downloader.Proxy.IsBypassed($url)) {# system proxy (pass through)$creds = $defaultCredsif ($creds -eq $null) {Write-Debug 'Default credentials were null. Attempting backup method'$cred = get-credential$creds = $cred.GetNetworkCredential();}$proxyaddress = $downloader.Proxy.GetProxy($url).AuthorityWrite-Debug "Using system proxy server '$proxyaddress'."$proxy = New-Object System.Net.WebProxy($proxyaddress)$proxy.Credentials = $creds$downloader.Proxy = $proxy}}return $downloader
}function Download-File {param ([string]$url,[string]$file)$downloader = Get-Downloader $url$downloader.DownloadFile($url, $file)
}function Download-Package {param ([string]$packageODataSearchUrl,[string]$file)$downloader = Get-Downloader $packageODataSearchUrlWrite-Output "Querying latest package from $packageODataSearchUrl"[xml]$pkg = $downloader.DownloadString($packageODataSearchUrl)$packageDownloadUrl = $pkg.feed.entry.content.srcWrite-Output "Downloading $packageDownloadUrl to $file"$downloader.DownloadFile($packageDownloadUrl, $file)
}function Install-ChocolateyFromPackage {param ([string]$chocolateyPackageFilePath = ''
)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"}$chocTempDir = Join-Path $env:TEMP "chocolatey"$tempDir = Join-Path $chocTempDir "chocInstall"if (![System.IO.Directory]::Exists($tempDir)) {[System.IO.Directory]::CreateDirectory($tempDir)}$file = Join-Path $tempDir "chocolatey.zip"Copy-Item $chocolateyPackageFilePath $file -Force# unzip the packageWrite-Output "Extracting $file to $tempDir..."if ($unzipMethod -eq '7zip') {$7zaExe = Join-Path $tempDir '7za.exe'if (-Not (Test-Path ($7zaExe))) {Write-Output 'Downloading 7-Zip commandline tool prior to extraction.'# download 7zipDownload-File $7zipUrl "$7zaExe"}$params = "x -o`"$tempDir`" -bd -y `"$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$process.StartInfo = New-Object System.Diagnostics.ProcessStartInfo($7zaExe, $params)$process.StartInfo.RedirectStandardOutput = $true$process.StartInfo.UseShellExecute = $false$process.StartInfo.WindowStyle = [System.Diagnostics.ProcessWindowStyle]::Hidden$process.Start() | Out-Null$process.BeginOutputReadLine()$process.WaitForExit()$exitCode = $process.ExitCode$process.Dispose()$errorMessage = "Unable to unzip package using 7zip. Perhaps try setting `$env:chocolateyUseWindowsCompression = 'true' and call install again. Error:"switch ($exitCode) {0 { break }1 { throw "$errorMessage Some files could not be extracted" }2 { throw "$errorMessage 7-Zip encountered a fatal error while extracting the files" }7 { throw "$errorMessage 7-Zip command line error" }8 { throw "$errorMessage 7-Zip out of memory" }255 { throw "$errorMessage Extraction cancelled by the user" }default { throw "$errorMessage 7-Zip signalled an unknown error (code $exitCode)" }}} else {if ($PSVersionTable.PSVersion.Major -lt 5) {try {$shellApplication = new-object -com shell.application$zipPackage = $shellApplication.NameSpace($file)$destinationFolder = $shellApplication.NameSpace($tempDir)$destinationFolder.CopyHere($zipPackage.Items(),0x10)} catch {throw "Unable to unzip package using built-in compression. Set `$env:chocolateyUseWindowsCompression = 'false' and call install again to use 7zip to unzip. Error: `n $_"}} else {Expand-Archive -Path "$file" -DestinationPath "$tempDir" -Force}}# Call Chocolatey installWrite-Output 'Installing chocolatey on this machine'$toolsFolder = Join-Path $tempDir "tools"$chocInstallPS1 = Join-Path $toolsFolder "chocolateyInstall.ps1"& $chocInstallPS1Write-Output 'Ensuring chocolatey commands are on the path'$chocInstallVariableName = 'ChocolateyInstall'$chocoPath = [Environment]::GetEnvironmentVariable($chocInstallVariableName)if ($chocoPath -eq $null -or $chocoPath -eq '') {$chocoPath = 'C:\ProgramData\Chocolatey'}$chocoExePath = Join-Path $chocoPath 'bin'if ($($env:Path).ToLower().Contains($($chocoExePath).ToLower()) -eq $false) {$env:Path = [Environment]::GetEnvironmentVariable('Path',[System.EnvironmentVariableTarget]::Machine);}Write-Output 'Ensuring chocolatey.nupkg is in the lib folder'$chocoPkgDir = Join-Path $chocoPath 'lib\chocolatey'$nupkg = Join-Path $chocoPkgDir 'chocolatey.nupkg'if (!(Test-Path $nupkg)) {Write-Output 'Copying chocolatey.nupkg is in the lib folder'if (![System.IO.Directory]::Exists($chocoPkgDir)) { [System.IO.Directory]::CreateDirectory($chocoPkgDir); }Copy-Item "$file" "$nupkg" -Force -ErrorAction SilentlyContinue}
}# Idempotence - do not install Chocolatey if it is already installed
if (!(Test-Path $ChocoInstallPath)) {# download the package to the local pathif (!(Test-Path $localChocolateyPackageFilePath)) {# 277行 Download-Package 这个注释掉# Download-Package $searchUrl $localChocolateyPackageFilePath}# Install ChocolateyInstall-ChocolateyFromPackage $localChocolateyPackageFilePath
}

Chocolatey 的安装相关推荐

  1. 基于windows平台的命令行软件安装工具Chocolatey的安装

    本文介绍Chocolatey的安装和使用 Chocolatey 这是基于.NET Framework 4以上的windows安装软件的命令行工具 安装 第一步,打开你的powershell.exe,使 ...

  2. chocolatey的安装与使用与chocolatey安装失败的解决方法

    chocolatey的安装与chocolatey安装失败的解决方法 具体的下载方法可以查看官网: https://chocolatey.org/install 安装过程中发现问题,在PowerShel ...

  3. Chocolatey离线安装步骤

    Chocolatey在Windows上离线安装步骤 一.Chocolatey介绍 chocolatey是一个包管理工具,类似Node.docker.yarn等.而chocolatey又可以很方便地安装 ...

  4. Windows软件管理工具Chocolatey的安装和使用

    一.概述 ​ 官网介绍Chocolatey 是一种软件管理解决方案,不同于您在 Windows 上体验过的任何其他解决方案.Chocolatey 带来了真正的包管理的概念,允许您对事物进行版本化.管理 ...

  5. Chocolatey的安装与使用

    Chocolatey的安装与使用 前言 一.Chocolatey的官网 二.安装 1. 系统要求 2. 安装步骤 3.安装图形化界面 三.其他命令 前言 Chocolatey是用于Windows系统的 ...

  6. Chocolatey离线安装方法

    By: Ailson Jack Date: 2020.05.05 个人博客:首页 | 说好一起走 本文在我博客的地址是:Chocolatey离线安装方法 | 说好一起走,排版更好,便于学习,也可以去我 ...

  7. 【Chocolatey】安装python3

    目录 前言 准备 安装python3 编写 python 程序 Helloworld 前言 win10 Chocolatey : 0.10.15 准备 安装Chocolatey.参考这里. 查找pyt ...

  8. Chocolatey离线安装

    参考链接:https://blog.csdn.net/sw3114/article/details/104299003?depth_1-utm_source=distribute.pc_relevan ...

  9. Chocolatey的安装和使用

    Chocolatey 文章目录 Chocolatey 一.Chocolatey是什么? 1.官网 2.安装文档 二.安装步骤 1.以管理员身份运行Power Shell 2.检查是否安装成功 三.安装 ...

最新文章

  1. python 下划线转驼峰
  2. ubuntu修改新增用户的目录_Ubuntu 18.04下创建新用户/目录、修改用户权限及删除用户的方法...
  3. 成功解决attrs = config.__dict__['__flags'] KeyError: '__flags
  4. (75)内核APC执行过程,分析 KiDeliverApc 函数
  5. Cloudera将被私有化,Hadoop时代或将落幕
  6. jenkins复制作业_Jenkins分层作业和作业状态汇总
  7. 详解centos7 YCM YouCompleteMe自动补全安装,亲测成功
  8. Angular属性型指令
  9. MORAN文本识别算法开源,刷新多个OCR数据集state-of-the-art
  10. linux 邮件附件 中文,linux bash下通过mailx发送中文内容显示为附件的解决
  11. 联想e540风扇清灰_实力强劲无惧挑战,联想异能者就是这么强悍
  12. LeetCode 11盛水最多的容器
  13. 求数组子序列和最大值
  14. Thinking in Java 16.3返回一个数组
  15. 小米wifi驱动 linux,树莓派2B 安装小米wifi驱动
  16. Overlay network
  17. JS 获得FileUpload1 的完整路径
  18. Testng的简介和使用
  19. 陶  朱  商  经
  20. 【英语阅读】纽约时报 | 你妈注定让你抓狂

热门文章

  1. 一导航(WebStack导航wordpress版)本地测试安装成功
  2. JS中setTimeout()的用法详解
  3. 微服务架构深度解析:你知道微服务的主要特性有哪些吗?
  4. Azkaban——安装指南
  5. Django做一个简单的博客系统(11)----搜索文章
  6. java多文件上传plupload控件实现多图片上传(二)
  7. Python-turtle绘画旅程第一站:哆啦a梦
  8. 那些有趣的codepen项目
  9. Python 图片转换(Image Conversion) (JPG ⇄ PNG/JPG ⇄ WEBP)
  10. 计算机行业职称考试大纲,2015年职称计算机考试大纲