SoFunction
Updated on 2025-03-10

The wonderful use of the propt function in PowerShell

This article introduces the Prompt function in PowerShell, and customizes the prompts of the PowerShell command line interface through the Prompt function.

Before designing the prompt function, the editor wanted to change the PowerShell command line prompt to zhanghong>, but I don't know if it is OK. After searching, I found the function propt. Let’s take a look at the following function definition:

Copy the codeThe code is as follows:

function prompt{
    "PS zhanghong> "
}

This is a very ordinary function, without any substantial difference. Moreover, the code in the function body is even more simple, and it directly outputs a string.
Put this function into PowerShell and execute it:
Copy the codeThe code is as follows:

PS C:\Users\zhanghong> function prompt{
>>     "PS zhanghong> "
>> }
>>
PS zhanghong>

Oh, my GOD! It's incredible! I just defined this function and haven't called it yet! The PowerShell command prompt is modified! Very good, very powerful!

Later, the editor also found that in PowerShell's propt function, you can do some interesting things. For example, I made the prompt a fixed string, but I want to know what the current path is, so I can't always use pwd. So the editor saw that a great man used this way. He put the current path on the title of the command line window, which was really invincible! In the future, no matter what the path becomes, the title will display the exact current path.

Copy the codeThe code is as follows:

function prompt{
    "PS zhanghong> "
    $ = (Get-Location)
}

If you don’t believe it, give it a try! The prompt function only needs to be defined, no need to be called!