How to load environment variables set by a batch script into PowerShell

Add this snippet to your $PROFILE:

function LoadBat {
  param(
    [Parameter(Position = 0, Mandatory)]
    [string] $BatPath
  )

  & "$env:SystemRoot\system32\cmd.exe" /C "`"$BatPath`" >NUL & set" |
    Select-String '^([^=]*)=(.*)$' | ForEach-Object {
      $name = $_.Matches[0].Groups[1].Value;
      $value = $_.Matches[0].Groups[2].Value;
      Set-Item -Path env:$name -Value $value
    }
}

After restarting your shell, use it like that:

LoadBat "${env:ProgramFiles(x86)}\Microsoft Visual Studio\2019\Professional\Common7\Tools\VsDevCmd.bat"

Go back to all notes

Page last modified: