PowerShell Core has plenty of built-in variables that give you immediate information about the environment you are working with. The following recipe will show you the most important ones.
Discovering the environment
Getting ready
In order to follow this recipe, you should have completed the installation of PowerShell Core for your operating system.
How to do it...
Please perform the following steps:
- Review the output of $PSVersionTable. With this variable, you'll always know which version and edition you are running.
- Try to execute Set-Location $PSHome; Get-ChildItem. This folder contains all PowerShell binaries necessary to run the shell.
- Have a look at the value of $pid. This variable always points to your own PowerShell process.
- Try running the Get-Item DoesNotExist cmdlet and afterward, view the contents of $Error. This variable collects errors that happen in your session. Not all errors collected here have been visible on the CLI.
- Try the following: $true = $false. You'll be pleasantly surprised that these variables are so-called constants and can't be changed.
- Have a look at the output of Get-Process | Format-Table Name,Threads. You'll notice that the threads always seem to stop at four elements.
- Display the contents of the variable, $FormatEnumerationLimit. The value of four isn't a coincidence. This variable governs how list output is formatted.
- Have a look at $PSScriptRoot. For some reason, this variable is empty. The reason is that this variable is only set when a script is executed. It then will point to the directory containing the script. $PSCommandPath will contain the entire script path.
- Run the following command: Set-Content -Path ~/test.ps1 -Value '$PSScriptRoot;$PSCommandPath'; ~/test.ps1. Examine the output; the first line contains the script directory, whereas the second line will show the full script path you executed.
- Lastly, try Get-Variable *Preference. These variables control the behavior of PowerShell regarding errors, warnings and more. In Chapter 2, Reading and Writing Output, we'll have a close look at those.
How it works...
Each time a new PowerShell session is started, a bunch of variables is registered and filled. You can always rely on those variables to exist and be present in your scripts. Many of those variables contain preferences for cmdlets, formatting, and output.
There's more...
In the following chapters, there'll be more. We'll continue using the built-in variables for different purposes.