Question

Difficulty: MediumBasic Scripting Languages and Constructs

A system administrator is writing a Windows PowerShell script (`.ps1`) to automate user environment auditing. The script needs to retrieve the built-in system environment variable for the logged-in username and display it to the console. Which of the following code snippets uses the correct syntax to reference an environment variable in PowerShell?

  1. Write-Output $env:USERNAMEAnswer
  2. B
    Write-Output %USERNAME%
  3. C
    Write-Output $USER
  4. D
    Write-Output %env:USERNAME%

Answer

The command line using 'Write-Output $env:USERNAME' correctly references an environment variable in PowerShell.
In Windows PowerShell, system environment variables are accessed via the environment drive provider using the 'env:prefixfollowedbythevariablename(suchasenv:' prefix followed by the variable name (such as env:USERNAME).

Step-by-Step Solution

1
Identify the target scripting runtime environment
The administrative task requires a native Windows PowerShell (.ps1) script construct.
Different scripting engines use distinct syntax rules for variable declaration and environment variable retrieval.
2
Apply PowerShell environment variable syntax rules
PowerShell exposes environment variables through the 'env:' drive namespace, which requires a leading dollar sign ($env:VariableName).
Using the $env: scope allows PowerShell to read directly from the system's environment variable table.

Key Concept

PowerShell Environment Variable Syntax
Rate this question