Question

Difficulty: MediumBasic Scripting Languages and Constructs

A systems administrator is updating a legacy Windows batch script (.bat) used during user logon to map a personalized directory path on a network share. The script needs to reference the standard environment variable that dynamically retrieves the currently logged-in account name. Which of the following syntax formats correctly accesses this environment variable inside a Windows batch script?

  1. %USERNAME%Answer
  2. B
    $env:USERNAME
  3. C
    $USERNAME
  4. D
    /USERNAME

Answer

The syntax `%USERNAME%` correctly references the environment variable in a Windows batch script.
In Windows Command Prompt batch scripts (.bat), environment variables are evaluated by surrounding the variable name with percent signs, such as `%USERNAME%`. When executed, `cmd.exe` replaces `%USERNAME%` with the current user's logon name.

Step-by-Step Solution

1
Identify the target scripting environment and requirement.
The requirement specifies a Windows Command Prompt batch script (.bat) referencing an environment variable.
Different scripting environments (.bat, .ps1, .sh, .py) use distinct variable evaluation syntaxes.
2
Determine the proper variable syntax for Windows batch (.bat) files.
Batch scripts enclose environment variable names in percent symbols, such as `%USERNAME%` or `%PATH%`.
This allows the command processor (cmd.exe) to expand the variable into its literal text value prior to command execution.

Key Concept

Windows Batch Script Environment Variable Syntax
Rate this question