It appears many of you are taken with the possibilities of PowerShell prompt functions. In previous posts, I alluded to the fact that you could do just about anything in a prompt function. Today I have an example of what I am talking about. The challenging part of creating a prompt function that does more is that you want it to run very, very quickly. The last thing you want is to wait several seconds for your prompt to return. With that in mind, here’s a prompt function that will display is a small list of servers is up or down.
ManageEngine ADManager Plus - Download Free Trial
Exclusive offer on ADManager Plus for US and UK regions. Claim now!
When I first started working on this I was calling Test-WSMan to verify if 4 computers were up and running. However, this took a few seconds per server which made the entire prompt function frustratingly slow. I toyed with the idea of running the test in a background job and displaying the results of the last job, but this too was very slow. Then I hit on the idea of using a runspace and a synchronized hashtable. This is an advanced topic so don’t feel bad if you don’t follow everything.
Think of the runspace as a separate and hidden PowerShell window. In the runspace, I’m running code to “ping” the servers with Test-WSMan every 5 seconds. That seemed like a reasonable amount of time. My prompt function is not intended as a high availability solution. The runspace updates a hashtable variable that is synchronized with my console session. This means I can access the hashtable and update my prompt function. The code for this function can be found on Github or you can copy it from here.
Because I am using Test-WSMan, this will not work on non-Windows platforms. But it will run on PowerShell Core on Windows. I have hardcoded my server names so you’ll need to edit the function. You could also modify the code to pass the names as a parameter for the runspace script.
When you first run the prompt function, it may take 5-10 seconds before you get a result.
The nice thing about the synchronized hash is that I can see the results. Here’s the prompt on PowerShell Core.
If you start having issues, you can delete the $TestHash variable from your session. The next time you press Enter the prompt function will recreate it. Or start a new PowerShell session and load the prompt function.
I have a few more fun and potentially useful prompt functions for later this week. Enjoy!
I used to have my old DOS prompt to display date and time and free disk space on a line on the bottom of the window. This was 25 years ago. Not a clue how I did it and before the days of Internet and cloud storage so scriot/.BAT file was probably on a 3.5″ floppy I threw out years ago! Will have to play with this