programing

Chocolatey 설치 후 새 세션을 열지 않고 PowerShell 세션 환경을 새로 고치는 방법

cafebook 2023. 10. 10. 20:57
반응형

Chocolatey 설치 후 새 세션을 열지 않고 PowerShell 세션 환경을 새로 고치는 방법

저는 GitHub 소스 코드를 로컬 머신에 복제하기 위한 자동 스크립트를 작성하고 있습니다.
스크립트에 Git을 설치한 후 실패하여 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 | %{ "$_" } 

오류:

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.

종료하지 않고 PowerShell을 재부팅하려면 무엇을 넣어야 합니까?

부트스트래핑 문제가 발생했습니다.

  • refreshenv에 대한 별칭은 일반적으로 다음 후 환경-variable 변경을 사용하여 현재 세션을 업데이트하는 데 사용하는 올바른 명령입니다.choco install ...지휘.

  • 하지만 Chocolatey 자체를 설치한 직후,refreshenv/Update-SessionEnvironment이러한 명령을 로드하는 것은 프로파일에 추가된 코드를 통해 이루어지므로 향후 PowerShell 세션에서만 사용할 수 있습니다.$PROFILE, 환경변수에 따라$env:ChocolateyInstall.

그건 그렇지만, 당신은 Chocolatey가 하는 일을 본받을 수 있어야 합니다.$PROFILE사용할 수 있도록 하기 위해 향후 세션에서 소스를 제공합니다.refreshenv/Update-SessionEnvironmentChocolatey를 설치한 후 바로 다음을 수행합니다.

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.
# Note: Using `. $PROFILE` instead *may* work, but isn't guaranteed to.
$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

참고: 원래 사용된 솔루션. $PROFILE대신에Import-Module ...Chocolatey 프로필을 로드합니다. Chocolatey에게 업데이트를 의존합니다.$PROFILE이미 그 시점에서그러나 열혈 코더는 이 업데이트가$PROFILE항상 일어나는 것은 아니기 때문에 믿을 수 없습니다.

새로움:

내가 원래 대답했던 오래된 접근법은 환경 변수들과 함께 a를 사용하는 몇가지 특이점들이 있습니다.;구분 기호PATH를 따로 처리하여 보상을 시도했지만 다른 변수가 있을 때도 있습니다.

이것이 새로운 접근법입니다. 스크립트 같은 것에 넣길 원할 수도 있습니다.몇 개의 파워셸 프로세스를 신속하게 구축해야 하는데, 이는 이상적이지는 않지만, 활성화된 환경에서 벗어나 출력물을 캡처할 수 있는 유일한 신뢰할 수 있는 방법입니다.

# Call a powershell process to act as a wrapper to capture the output:
& ([Diagnostics.Process]::GetCurrentProcess().ProcessName) -NoP -c (
# String wrapper to help make the code more readable through comma-separation:
[String]::Join(' ', (
# Start a process that escapes the active environment:
'Start-Process', [Diagnostics.Process]::GetCurrentProcess().ProcessName,
'-UseNewEnvironment -NoNewWindow -Wait -Args ''-c'',',
# List the environment variables, separated by a tab character:
'''Get-ChildItem env: | &{process{ $_.Key + [char]9 + $_.Value }}'''
))) | &{process{
  # Set each line of output to a process-scoped environment variable:
  [Environment]::SetEnvironmentVariable(
    $_.Split("`t")[0], # Key
    $_.Split("`t")[1], # Value
    'Process'          # Scope
  )
}}

이전:

최선을 다해 원라이너로 만들었지만 PATH 변수는 특별한 핸들링이 필요하기 때문에 바보같이 긴 줄을 만들지 않고는 할 수 없었습니다.긍정적인 측면에서는 타사 모듈에 의존할 필요가 없습니다.

foreach ($s in 'Machine','User') {
  [Environment]::GetEnvironmentVariables($s).GetEnumerator().
  Where({$_.Key -ne 'PATH'}) | ForEach-Object {
    [Environment]::SetEnvironmentVariable($_.Key,$_.Value,'Process') }}

$env:PATH = ( ('Machine','User').ForEach({
  [Environment]::GetEnvironmentVariable('PATH',$_)}).
  Split(';').Where({$_}) | Select-Object -Unique ) -join ';'

코드는 프로세스 범위가 정해져 있기 때문에 문제가 생길 염려가 없습니다(테스트 해봤습니다).


두 모두 의 환경 를 제거하지 를 :$env:FOO = 'bar'는 중 'FOO'다를고합니다.$env:FOO입니다를(를) 합니다.bar위의 코드 중 하나가 실행된 후에도.

Update-Session Environment:

Chocolatey 패키지 설치 중에 발생했을 수 있는 모든 환경 변수 변경 사항으로 현재 파워셸 세션의 환경 변수를 업데이트합니다.

그것은 초콜릿 맛이 난 후에도 그 변화가 여전히 효과적인지를 시험해 볼 것입니다.

한 가지 쉬운 , 입니다를 입니다.git.

파워셸에서 깃을 호출하는 방법:

new-item -path alias:git -value 'C:\Program Files\Git\bin\git.exe'

그러면 다음을 시도해 볼 수 있습니다.

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

저는 로테크 솔루션에 찬성합니다.

$env:Path += ";C:\Program Files\Git\bin"

언급URL : https://stackoverflow.com/questions/46758437/how-to-refresh-the-environment-of-a-powershell-session-after-a-chocolatey-instal

반응형