It’s simply not everyday that Rob Sewell (@sqldbawithbeard) places a link on Twitter to your blog. Yours, as in mine, but here we are. That was yesterday.
Read-Host with a Previous Value #powershell by @thetommymaynard https://t.co/KourPwhDve
— Rob He/Him – Not an AI generated speaker (@sqldbawithbeard) September 18, 2017
Today, knowing this is out there, I decided to add a bit more to this short post with a second installment. In this post, I’ve written a few changes to the single If statement from Part I. While it was a simple statement to see if I could reuse a previously stored value in the first installment, it’s a bit more full featured now.
We’re getting away from statically setting the default user. We’ll actually let the user assign that value. This determination — whether there’s a default user or not — defines our prompt message, which is most of what’s been added.
If ($User) { $Prompt = "Press Enter for the last user [$User], or enter a new user" } Else { $Prompt = "Please enter a new user" } If (($Result = Read-Host -Prompt $Prompt) -eq '' -or $Result -eq $User) { "You're using the previously used ""$User"" user." } Else { "You're using the previously unused ""$Result"" user." $User = $Result }
I won’t bother including any examples of the running code, but do run the example yourself if you’re interested. Remember to clear or remove the $User, $Prompt, and $Result variables if you want to start fresh. The following command will remove those variables, if you find you need it before a new run.
Remove-Variable -Name User,Prompt,Result -ErrorAction SilentlyContinue
And that’s it. Thanks for the link to the blog, Rob!