PowerShell CI Environment
The CI environment is the set of values a build script reads from outside itself. CI means continuous integration, the habit of building and testing code often.
Set and read a variable
Assigning to $env:NAME stores the value for this process. Reading it back shows the same value.
$env:BUILD_NUMBER = "42"
$env:BUILD_NUMBERA missing variable is empty
A name that was never set reads as empty. An if test treats it as not set.
if ($env:MY_MISSING_VALUE) { "set" } else { "not set" }Read the exit code of a native command
The Linux command false always fails, and true always succeeds. Their exit codes are 1 and 0.
false
$LASTEXITCODE
true
$LASTEXITCODEExample
$env:BUILD_NUMBER = "7"
false
if ($LASTEXITCODE -ne 0) { "Build " + $env:BUILD_NUMBER + " failed" } else { "Build " + $env:BUILD_NUMBER + " passed" }Key points
- Environment variable: a named value set outside a script that the script can read.
- Use $env:NAME to read the environment variable named NAME.
- Process-local: a value set in a script lasts only for that running process.
- Exit code: a whole number a native command leaves behind when it finishes.
- Native command: a command from the operating system, not a PowerShell cmdlet.
- Success code: an exit code of 0 means the command succeeded, and any other number means it failed.
In this example, the script sets a build number, runs a failing native command, checks the exit code, and reports that the build failed.
Note
PowerShell cmdlets do not set $LASTEXITCODE. Only native commands do.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
A native command fails. What is $LASTEXITCODE?