5.4. Prompts

PowerShell allows you to customize the command prompt. The prompt is defined by the prompt function. You can include a function definition for the prompt function in a profile file.

The prompt function returns a string, which is then displayed to the user at the beginning of each line in the command shell window.

The function definition shown earlier in the example profile.ps1 file is the default:

function prompt
{
     "PS " + $(get-location) + "> "
}

This definition uses the literal string PS followed by a space character, followed by the result returned by the get-location cmdlet, followed by a right arrow, followed by a space character. The get-location cmdlet, as its name suggests, retrieves the current location. The concatenated string is then displayed at the beginning of each line.

In principle, you can use any PowerShell code to generate a string to use as the prompt. For example, if you want to display the date and time as a prompt, you can use the following definition:

function prompt
{
 "" + $(get-date) + " > "
}

Figure 5-17 shows the use of the function and the new prompt.

Figure 5.17. Figure 5-17

Notice that there is an empty string (paired quotation marks with nothing between them) as the first part of the function definition. If you use

$(get-date) + " > "

in the third line, the desired prompt will not be displayed. See Figure 5-18.

Figure 5.18. Figure ...

Get Professional Windows® PowerShell now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.