Empty GITHUB_ENV variables on PowerShell

I am running a job on windows-latest and after setting a variable in a step it is empty in the following ones:

# STEP 1
Write-Host "workingDir=$workingDir" |
    Out-File -FilePath $env:GITHUB_ENV -Encoding utf8 -Append

# STEP 2
Write-Host "env:workingDir '$env:workingDir'"

I tried without specifying the shell and the step uses PowerShell 7.0:
C:\Program Files\PowerShell\7\pwsh.EXE -command ". '{0}'"

Then I tried specifying shell: powershell and the step uses Windows PowerShell 5.1:
C:\windows\System32\WindowsPowerShell\v1.0\powershell.EXE -Command "& '{0}'"

Finally I tried specifying shell: pwsh -Command "& '{0}'" and the step uses PowerShell 7.0:
C:\Program Files\PowerShell\7\pwsh.EXE -Command "& '{0}'"

It would be great if someone could help me find out what I am doing wrong.


The Environment files docs use echo in PowerShell.

After some investigation I found out that echo is an alias for Write-Output not Write-Host which only outputs to the console, not to stdout.

I ended up using Add-Content which uses UTF8 (without BOM) by default:

Add-Content -Path $env:GITHUB_ENV -Value "name=$value"

This is not the case in PowerShell, only in PowerShell Core (pwsh)! If we assume pwsh, then you can simplify it to this:

echo "{name}={value}" >> $Env:GITHUB_ENV

For maximum compatibility, you may go with the docs recommendation:

echo "{name}={value}" | Out-File -FilePath $Env:GITHUB_PATH -Encoding utf8 -Append

For maximum compatibility it is enough to add -Encoding UTF8 to Add-Content which avoids piping and using the echo alias (non idiomatic).

Shouldn’t it be -Encoding utf8NoBOM?

Not if you take into consideration the docs recommendation and the absence of utf8NoBom from Windows PowerShell 5.1 (powershell)

I see. Just checked locally that Add-Content doesn’t write a BOM if the target file does not exist yet. It does add a line break (\r\n) automatically, but so does Out-File. What’s problematic is that Out-File writes a BOM if it’s a new file and that there is no utf8NoBOM encoding available.

FWIW, GitHub-hosted Windows runners provide the following PS versions:

powershell pwsh
windows-2016 5.1.14393.3866 7.1.0
windows-2019 5.1.17763.1490 7.1.0