Chocolatey离线(offline)安装流程
创始人
2024-09-26 00:49:09
0

首先要确定你能下载什么版本的chocolatey,具体版本对照参考该网址:

Chocolatey Software Docs | Chocolatey Components Dependencies and Support Lifecycle

从这个网站可以找到安装和卸载的详细说明。

Chocolatey Software Docs | Setup / Install

详细步骤如下:

步骤 1:下载 Chocolatey 安装包

Chocolatey Software | Chocolatey 2.3.0

点击左下角的download下载你想要的副本,记住你的安装路径。

步骤2:转移文件位置

为了避免C盘爆满,将下载的 .nupkg 文件复制到离线机器上的某个目录。例如,将文件复制到 C:\offline-choco 目录。博主转移到了D:\user-unity3D\user-chocolatey。

步骤3:创建和运行安装脚本

①将你提供的脚本保存为一个.ps1文件,例如 install_choco_offline.ps1。

# 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://community.chocolatey.org/api/v2/ # If you are using Nexus, always add the trailing slash or it won't work # === EDIT HERE === $packageRepo = ''  # 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"  $localChocolateyPackageFilePath = Join-Path $env:TEMP 'chocolatey.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.Major    if ($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]::DefaultCredentials   if (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:chocolateyIgnoreProxy   if ($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:chocolateyProxyPassword     if ($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 = $defaultCreds       if ($creds -eq $null) {         Write-Debug 'Default credentials were null. Attempting backup method'         $cred = get-credential         $creds = $cred.GetNetworkCredential();       }        $proxyaddress = $downloader.Proxy.GetProxy($url).Authority       Write-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 $packageODataSearchUrl    Write-Output "Querying latest package from $packageODataSearchUrl"   [xml]$pkg = $downloader.DownloadString($packageODataSearchUrl)   $packageDownloadUrl = $pkg.feed.entry.content.src    Write-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 package   Write-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 7zip       Download-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 install   Write-Output 'Installing chocolatey on this machine'   $toolsFolder = Join-Path $tempDir "tools"   $chocInstallPS1 = Join-Path $toolsFolder "chocolateyInstall.ps1"    & $chocInstallPS1    Write-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 path   if (!(Test-Path $localChocolateyPackageFilePath)) {     Download-Package $searchUrl $localChocolateyPackageFilePath   }    # Install Chocolatey   Install-ChocolateyFromPackage $localChocolateyPackageFilePath }
  • 修改$localChocolateyPackageFilePath = ‘你的安装路径’,这个在46行。例如我修改成:$localChocolateyPackageFilePath = ‘D:\user-unity3D\user-chocolatey\chocolatey.2.3.0.nupkg’
  • 注释掉:Download-Package $searchUrl $localChocolateyPackageFilePath。这个在277行。

②打开离线机器上的powershell(以管理员身份运行)

按Windows键快捷输入powershell,右键管理员运行。执行:iex "你的ps1文件保存路径\install_choco_offline.ps1"

iex "D:\user-unity3D\user-chocolatey\install_choco_offline.ps1"

大概5-10s后出现如下图所示内容,则安装完毕:

这样就安装完毕啦!

可以通过如下命令检查是否安装成功:

choco -v 

输出版本号:

也可以通过如下命令输出安装路径:

[System.Environment]::GetEnvironmentVariable('ChocolateyInstall', [System.EnvironmentVariableTarget]::Machine)

输出路径则成功:

可能出现的问题:

尽管你已经以管理员身份运行PowerShell,执行策略仍然可能阻止脚本的运行。

临时设置执行策略

  • 在管理员模式下的PowerShell窗口中,输入以下命令来临时绕过执行策略,然后再执行上面的iex命令:
  • Set-ExecutionPolicy Bypass -Scope Process -Force 

相关内容

热门资讯

安卓系统app更新软件,And... 亲爱的手机控们,你们有没有发现,最近你的手机里那些熟悉的APP们,好像都悄悄地换上了新装呢?没错,安...
手机怎么安双卡安卓系统,轻松实... 你有没有想过,拥有一部可以同时使用两张SIM卡的手机是多么的方便呢?想象一张卡用来工作,另一张卡用来...
安卓系统卸载软件api,功能与... 手机里的软件越来越多,是不是感觉内存都要不够用了?别急,今天就来给你揭秘安卓系统卸载软件的神秘面纱,...
miui操作系统和安卓系统,深... 亲爱的手机控们,今天咱们来聊聊一个让无数米粉心动的系统——MIUI操作系统,还有那个它背后的老大哥—...
原生安卓系统使用教学,原生安卓... 哇,你手里拿的那部手机,是不是也觉得它有点儿特别呢?它可能没有那些花里胡哨的界面,但它却有着自己独特...
安卓系统玩咸鱼之王,三国名将助... 你有没有发现,最近安卓系统上的游戏圈里,有一款叫做《咸鱼之王》的游戏火得一塌糊涂?没错,就是那个让你...
鸿蒙1.0系统是安卓系统吗,揭... 你有没有听说最近华为的鸿蒙1.0系统?是不是有点好奇,这鸿蒙1.0系统是不是安卓系统的“亲戚”呢?别...
优盘安卓系统用桃,U盘安装An... 你有没有想过,你的电脑也能变身成安卓手机?没错,就是那种可以安装各种APP、玩游戏的安卓手机!这可不...
怎样使用安卓8系统,安卓8系统... 你有没有想过,你的安卓手机其实是个小智能助手,只要你会使用,它能帮你做很多事情呢!今天,就让我来带你...
鼎威安卓系统版本,性能升级与用... 你有没有发现,现在车机系统越来越智能了?这不,鼎威的安卓系统版本就让我眼前一亮。想象坐在车里,手指轻...
安卓系统安装抢红包,轻松成为抢... 亲爱的手机控们,是不是每次微信群里抢红包都感觉手慢无?别急,今天我要给你揭秘如何在安卓系统上轻松安装...
写ios系统和安卓系统的人,揭... 你有没有想过,那些默默无闻的程序员们,他们是如何创造出我们每天离不开的iOS系统和安卓系统呢?想象他...
安卓系统设计尺寸规范,适配与优... 亲爱的设计师们,你是否在为安卓系统的设计尺寸规范而头疼?别担心,今天我要带你一起探索这个神秘的领域,...
旧主机改安卓系统,安卓系统改造... 亲爱的读者们,你是否有过这样的经历:家里的旧主机闲置在角落,看着它那略显过时的外观,心里不禁感叹:“...
安卓系统里有趣的,尽在掌握 探索安卓乐园:那些让你笑出声的趣味游戏 开篇:手机里的欢乐小天地想象你手握一部安卓手机,屏幕上跳动...
法兰规格查询系统安卓,安卓版功... 你有没有想过,在繁忙的工程现场,如何快速找到合适的法兰规格呢?别急,今天就来给你揭秘一个神器——法兰...
目前安卓系统最高配置,极致性能... 你有没有发现,现在的手机越来越厉害了,就像是科幻电影里的高科技产品一样。今天,咱们就来聊聊这个话题:...
安卓修改系统返回键,个性化设置... 你有没有发现,手机里的那个小小的返回键,有时候就像是个顽皮的小家伙,让你摸不着头脑?别急,今天就来教...
安卓订餐系统教程视频,从设计到... 你是不是也和我一样,每天忙碌的生活中,最期待的就是那一顿美味的午餐或晚餐呢?现在,有了安卓订餐系统,...
安卓系统限制外部软件,探索外部... 亲爱的手机控们,你是否曾遇到过这样的烦恼:明明打开了“未知来源”,却还是无法安装那些心仪的外部软件?...