如何在Chocolatey安装后刷新PowerShell会话的环境,而无需打开新会话

Pri*_*ani 9 powershell installation refresh environment-variables chocolatey

我正在编写自动脚本,用于将GitHub源代码克隆到本地机器.
我在我的脚本中安装Git后失败了,它要求close/open powershell.
所以我无法在安装Git后自动克隆代码.

这是我的代码:

iex ((New-Object System.Net.WebClient).DownloadString('https://chocolatey.org/install.ps1'))
 choco install -y git
 refreshenv
 Start-Sleep -Seconds 15

 git clone --mirror https://${username}:${password}@$hostname/${username}/$Projectname.git D:\GitTemp -q 2>&1 | %{ "$_" } 
Run Code Online (Sandbox Code Playgroud)

错误:

git : The term 'git' is not recognized as the name of a cmdlet, 
      function, script file, or operable program. 
      Check the spelling of the name, or if a path was included, 
      verify that the path is correct and try again.
Run Code Online (Sandbox Code Playgroud)

请告诉我应该在不退出的情况下重新启动PowerShell?

mkl*_*nt0 12

你有一个自举问题:

  • refreshenv(别名Update-SessionEnvironment)通常是用于在命令后使用环境变量更改来更新当前会话的正确choco install ...命令.

  • 但是,在安装Chocolatey本身之后,refreshenv/ self本身Update-SessionEnvironment仅在将来的 PowerShell会话中可用,因为通过$PROFILE基于环境变量添加到配置文件的代码加载这些命令$env:ChocolateyInstall.

也就是说,您应该能够模仿 Chocolatey $PROFILE在未来会话中所做的事情,以便能够在安装Chocolatey之后立即使用refreshenv/ Update-SessionEnvironment立即使用:

iex ((New-Object System.Net.WebClient).DownloadString('https://chocolatey.org/install.ps1'))

choco install -y git

# Make `refreshenv` available right away, by defining the $env:ChocolateyInstall variable
# and importing the Chocolatey profile module.
$env:ChocolateyInstall = Convert-Path "$((Get-Command choco).path)\..\.."
Import-Module "$env:ChocolateyInstall\helpers\chocolateyProfile.psm1"

# refreshenv is now an alias for Update-SessionEnvironment
# (rather than invoking refreshenv.cmd, the *batch file* for use with cmd.exe)
# This should make git.exe accessible via the refreshed $env:PATH, so that it can be 
# called by name only.
refreshenv

# Verify that git can be called.
git --version
Run Code Online (Sandbox Code Playgroud)

注意:使用原始解决方案. $PROFILE而不是Import-Module ...加载Chocolatey配置文件,依赖于Chocolatey $PROFILE已在此时更新.然而,ferventcoder指出这种更新$PROFILE并不总是发生,所以不能依赖.

  • 配置文件重新加载是必须的,否则有时 refreshenv 无法工作! (2认同)
  • 如果你喜欢假设(我对此很糟糕),你也可以使用 `Import-Module "$env:ProgramData\chocolatey\helpers\chocolateyInstaller.psm1"; Update-SessionEnvironment` 其中 `$env:ProgramData\chocolatey` 是 Chocolatey 自行安装的默认路径。 (2认同)