When you first start using the PowerShell on your Windows machine more often, I am pretty sure that you want to customize the looks (and functionality) of this blue “blob” with white text. One aspect is to modify the Prompt (the line of text which appears at the beginning of each line).
The default configuration shows the whole path to the current working-directory; while this can be very helpful, I find it very annoying that the Prompt-text takes up 70% of my screen width when working in heavily nested directories (or the registry). So I decided to change it. This is actually very easy as the Prompt is generated by a single PowerShell function you can simply overwrite.
The function’s name is, unsurprisingly,
prompt. To be more specific, we are looking for the
prompt-function inside the global namespace. So, to overwrite it we just have to redefine it:
And done! - Kind of… A static text is boring and moreover, useless in terms of information. Of course, you can recreate the default bash-prompt (just put a “$” instead of “my new Prompt text”) but I personally like to get at least information about the current directory.
Luckily, dynamic Prompt-text is as easy to create. Because the Prompt gets created by a simple function which gets called after each command, you can put any lines of code in there.
I quickly gonna show you a view common building-blocks you can use:
Keep in mind, when you want to use multiple of them together, you either have to put them all together in one-string or use the
Write-Host function with the
-nonewline-switch. Using the second method, you can can also specify the color of the text (yeah, eye-candy!!).
I think that enough to get you started. Of course, you can put far more complex code in there; but, what ever you do, don’t forget that the function gets executed after every command you enter into the shell. So, you don’t want to put anything time consuming in there.
That said, you can use the
prompt function to execute code which is not related to styling your Prompt. Here is an example, where I create a variable which holds the last executed command as string inside this function.
I definitely don’t know if you are meant to do that, or if there is a better way to have code executed after each command; but, it seems to work so far.
Lastly, there are two things left to mentioned. First, to make your custom prompt persistent (and not only for one PowerShell session), you have to put the code inside of your Profile (you can learn about that here, for example). And second, some PowerShell-extensions (most famously PoshGit) also manipulate the Prompt by overwriting the
prompt-function. So, be aware that this will interfere with your changes.