The Pester Book Chapter Review (1)

Table of ContentsMy Introduction

Pester. Have you heard about it? I should hope you’ve at least, heard of it.

I know the exact moment I realized that I needed Pester, and decided I would learn it backwards and forwards, once for all. You’ll realize the moment too, if you haven’t already. Before that, providing it hasn’t happened, you need to know a little about what Pester is and what it does, so that when the day comes, you’ll have enough introductory information to now know that it’s a requirement in your life. It happens.

I was working an AWS Windows project that hadn’t yet included Active Directory. In this project and its sub projects, I was essentially creating and configuring Windows workgroup computers. If you consider that the project required a good deal of security and that we didn’t have an Active Directory environment to leverage, you can imagine that I had several settings to edit, in order to secure our machines.

The environments were built using AWS CloudFormation and a couple PowerShell modules that often included several functions. For each sub project, I built a new stack and waited for my instances and other resources to become available. When my instances were completed, I’d jump on them via Remote Desktop and start poking around. Were my users created? Was my SSL certificate for Remote Desktop in place? Were my PowerShell modules in place? Were my software installers in place? Were all the Registry settings applied? I was doing a “quick” and manual visual spot check to make sure my systems were configured correctly. Me, someone that’s dedicated to automation, was doing these things manually. I’d literally remotely connect to an instance, open the PowerShell ConsoleHost, and enter a string of commands that looked like this:

PS > regedit; certlm.msc; compmgmt.msc; ii 'c:\Program Files\WindowsPowerShell\Modules'

The above commands would open up the different graphical utilities that I needed, in order to ensure my automation had run successfully. I could check my registry settings, I could check to see if my certificate was imported, I could check to see if my users were created, and I could check to see if my PowerShell modules were in place. I was doing this manually, even when I knew there was a better way.

I repeatedly thought, I should write a function to do these checks for me. But why write another function? Why not use what’s already been built-in to test my system? Why not improve my project and get more experience with Pester at the same time?

Well, I did. After all those manual checks on my instances, I was just thrilled to see all those green lines produced by Pester, taking milliseconds of time, to remind me of all the time I had already wasted. But I’m okay with it now, as this project presented me an opportunity to really begin to appreciate and utilize Pester. And in that, the time and effort of Adam Bertram.

Follow along as I read Adam’s The Pester Book published on Leanpub.com. I’m not going to teach you Pester per se, but I’m going to write about as though we’re reading the same book together — Adam’s book — and share my thoughts as I do. You ought to get a copy and follow long; we’ll learn this better together. For the foreseeable future, let’s make this blog a weekly review of what we’ve read, so you and I can potentially get more out of our reading. Maybe we’ll do more than a single chapter per week — we’ll see. I’ll be back soon with the first installment; therefore, you should get your copy of The Pester Book today!

Write Functions, Not Scripts – Part V

I like how my assumption that Part IV of Write Functions, Not Scripts wouldn’t be a worthy contender to the previous three parts (P1, P2, P3). Seriously, I didn’t think it compared, and if I’m not mistaken, it’s been the most popular post in this series thus far.

It’s a simple concept though: short, simple, single-purposed is sufficient for writing functions. Think small, easier to troubleshoot code. Say you have five functions that run in succession — one right after the other. The point at which things break will likely remove 4 of the 5 functions as areas you even need to review. That means you’re troubleshooting a fifth of the code the scriptwriter would have to review. Functions are a no-brainer. Well, they ought to be, anyway.

Time for some more thoughts on why functions over scripts. Hey, ever see one of these in a script?

$UserCount = 10
# When using in production, please comment out the above line.
# Then, uncomment the below line.
# $UserCount = 20

This is why we have a Read-Host. This, would be better.

$UserCount = Read-Host -Prompt 'Enter the preferred User Count'

Before blogging was my main gig, you might find me scouring various forums more often and helping others (and secretly learning more, too). A good number of people were getting their input via the Read-Host cmdlet. It’s nice and all, but by itself, there’s a bit of mystery as to what a user might enter. While I’m expecting 10, or 20, I could end up with all kinds of obnoxious values.

$UserCount = Read-Host -Prompt 'Enter the preferred User Count'
Enter the preferred User Count: DogCatMom5
# Huh!?

Inside a Do loop construct, we can better control the acceptable input.

Do {
    $UserCount = Read-Host -Prompt 'Enter the preferred User Count'
} Until ($UserCount -eq 10 -or $UserCount -eq 20)
Enter the preferred User Count: 1
Enter the preferred User Count: 2
Enter the preferred User Count: 3
Enter the preferred User Count: 4
Enter the preferred User Count: 5
Enter the preferred User Count: 6
Enter the preferred User Count: DogCatMom5
Enter the preferred User Count: 10

But there’s still a better way. Function’s allow for parameters and so, as absolutely as best as we can, we need to separate our lives — and our function writing — from Read-Host. If it’s ever in a function, and I’ll agree that it can happen, there ought to be really great reason as to why. We’ll close out today’s post with a simple function example that uses parameters. This is such a huge benefit.

Function Test-ParamsInAFunction {
    Param (
        $Number,
        $Letter
    )
 
    If ($Number -and $Letter) {
        Write-Output -InputObject "You have entered the number $Number, and the letter $Letter."
    } ElseIf ($Number) {
        Write-Output -InputObject "You have entered the number $Number."
    } ElseIf ($Letter) {
        Write-Output -InputObject "You have entered the letter $Letter."
    } Else {
        Write-Output -InputObject "You have not entered a number or letter."
    }
}
Test-ParamsInAFunction
Test-ParamsInAFunction -Number 5
Test-ParamsInAFunction -Letter X
Test-ParamsInAFunction -Number 10 -Letter D

You have not entered a number or letter.
You have entered the number 5.
You have entered the letter X.
You have entered the number 10, and the letter D.

Functions can handle run time delivered values. There’s no more opening up scripts and adding and removing static comments and variable assignments. There’s no using Read-Host inside our scripts and functions (unless, again, you’ve got a really great reason), even if, you’re using a language construct to protect the acceptable values. Before we full on wrap up, let me show you how to make a parameter only accept the 10 and 20 values.

Function Test-ParamsInAFunction {
    Param (
        [ValidateSet(10,20)]
        $Number
    )
    ...
}

See you again next time.

PowerShell.org Amazing PowerShell Contributors Event

There was a time when the PowerShell.org PowerShell Hero program was a regular thing. Well, not all good things come to an end. Some, just need a temporary hiatus. And as best as I can tell, that’s exactly what we have here. But now, it’s back!

I thought I’d take a quick moment to write today, in order to give their recognition program one last final push, during the last day for nominations. Yes, you read that right, the nomination period is just about done. If someone’s helped you with PowerShell, then take a moment to nominate them.

If you haven’t already, or even if you have, head over to PowerShell.org, read the intro and then take the quick survey. Nominate people that deserve a thank you; that deserve recognition for their part — no matter how big, or how small — in making the PowerShell community what it is, and has been.

Write Functions, Not Scripts – Part IV

If you haven’t been with us in the previous three posts (this one, this one, and this one), we’ve been discussing why functions, over scripts. If you haven’t already, it’s time to change your mindset.

The idea is to write small, concise, single-purposed, chunks of code. We call these functions. What we don’t need… is long, overly complex, multi-purposed scripts. We’ve got to stop the scripting mentality. You know the one… you’re writing a script and your next thought is, now I need to do this…and then you write lines and lines beneath that which has already written. Now you have a multipurpose script and no clear end in sight.

It’s pretty simple: the longer the script, the more pieces to troubleshoot and when adding new features, the more potential areas to make errors. You’re creating more confusion. The whole process of script writing can easily and quickly get away from you. In one moment you add one solution, and then in another, you add more solutions to other problems you want to solve, and it’s all in a single file. Ugh.

That was it. Start writing in a single purposed methodology. Even if you’re not going not to write in functions beginning tomorrow morning, like you should, start scripting in single purposed scripts. If you need it, make that your first step. I’m not writing for my own benefit this evening; I’m writing for yours. You’re going to love being a function writer. You just need to make this the week you start, if you haven’t already. Here, I’ll get you started:

Function Get-ItDone {
    # Add your code here.
}
Get-ItDone

Alright, see you next time.

Write Functions, Not Scripts – Part III

First off, I have to say, the first two posts in this series have been very successful. Nearly 200 visitors on a Saturday and then a Sunday, too — that’s unheard of during the weekend. And to think, these two posts: Part I and Part II, have felt like some of the most distracted and unpredictable writing of mine to date, and I’ve been at this for almost four years straight, without a missed month.

Okay, to continue with a distraction, in Write Functions, Not Scripts — Part II, I showed a picture of the fog on my cul-de-sac in Tucson, AZ (the desert) last Friday. Here’s that picture now. That fog, is not typical for us. Maybe it happens once a year.

I mentioned that I’d include the typical view, and so here’s a picture from Saturday — just one day later. And that’s, what it normally looks like around here.

Moving along, as if there’s a PowerShell related topic at hand. So, here’s one reason for functions, over scripts: it’s variables. Let’s move out the fog, and explain.

When we’re developing scripts, we often create variables and assign them values at the top of our code. Normal stuff. The problem is that when we go to execute the script a second (or third, or fourth) time, the variables in our script have already been assigned a value, and that may make our results incorrect. This can lead to confusion and wasted time, incorrect results, and extra lines of unnecessary commands to initialize variables. Stop initializing, and then re-initializing, variables.

Let’s take a look at an example.

In each pass though the below ForEach-Object cmdlet, we set the $User variable to my name with the number of the current pass at the end. Then, we increase the $Count variable by 1. Take a look at the below results. Everything looks perfect. My name includes the current iteration through the loop, and the count matches, as it should.

1..5 | ForEach-Object {
    $User = "tommymaynard$_"
    $Count++

    "Count: $($Count)"
    "User: $User"
}

Count: 1
User: tommymaynard1
Count: 2
User: tommymaynard2
Count: 3
User: tommymaynard3
Count: 4
User: tommymaynard4
Count: 5
User: tommymaynard5

Now, let’s run it again.

1..5 | ForEach-Object {
    $User = "tommymaynard$_"
    $Count++

    "Count: $($Count)"
    "User: $User"
}

Count: 6
User: tommymaynard1
Count: 7
User: tommymaynard2
Count: 8
User: tommymaynard3
Count: 9
User: tommymaynard4
Count: 10
User: tommymaynard5

We didn’t want to continue to increase the $Count variable past five, but because we’re scripting, we did it anyway. Writing something like this would required a Remove-Variable, or Clear-Variable command, when the final loop was done. Annoying, and without it, when you’re scripting, you’re going to have inaccuracies.

With functions, we don’t ever need to reinitialize variables to their default values. And of course, we don’t need to remove them, or clear them, before our code is run a second, or third time. This isn’t to say you’ll never change the value of a variable inside a function, it’s to say that variables in a function don’t typically exist before, or after, a function is executed.

Function Show-CountAndUser {
    1..5 | ForEach-Object {
        $User = "tommymaynard$_"
        $Count++

        "Count: $($Count)"
        "User: $User"
    }
}

PS > Show-CountAndUser
Count: 1
User: tommymaynard1
Count: 2
User: tommymaynard2
Count: 3
User: tommymaynard3
Count: 4
User: tommymaynard4
Count: 5
User: tommymaynard5

Okay, that was the first execution. One through five: it looks good. And here’s, the second execution.

PS > Show-CountAndUser
Count: 1
User: tommymaynard1
Count: 2
User: tommymaynard2
Count: 3
User: tommymaynard3
Count: 4
User: tommymaynard4
Count: 5
User: tommymaynard5

Ah, perfect! Write functions, and stop worrying about having to set, and reset, variables. Use the variable scope provided by functions — it wants to help you. It’s one reason for functions over scripts. Back again later.

Part IV is now available.

Write Functions, Not Scripts – Part II

In Part I of this series, I was supposed to begin offering reasons as to why someone would want to stop writing scripts, and start writing functions. I got a bit distracted. Instead, we discussed making an easy, and mostly meaningless, function. The reasoning for this, was because I get this feeling that moving from a script writer to a function writer can be a unsettling endeavor for some. I liken it to bicycle training wheels. They’re so easy, and reliable. It’s just not until you take them off, and get your balance, that you suddenly realize all the things they actually kept your from doing. Learn to balance this bike, and then you can start jumping off your makeshift ramp in the middle of the cul-de-sac, instead of just riding around it.

Speaking of cul-de-sacs, here’s another distraction. It’s our view from Friday morning. That’s not what it usually looks like in Tucson, AZ. Fog is really, really rare. In one of these follow ups, I’ll be sure to include our typical desert view, uninterrupted by “winter” type weather events.

Functions can get advanced, sure, but once you know a few things about them, you’ll never look back. You’ll continue to learn more and more about them. There’s a whole new level of being proud of your work, as you transition to function writing. You’re going to sleep better at night knowing you’ve written five singled-purposed functions vs. that one long script you secretly hate to open and troubleshoot. Maybe, it’s not even a secret.

Look, at the end of the day, a function is nothing more than a scriptblock you can invoke by entering its name. You run commands all the time, maybe even a few, one right after the other. Now you can do the same thing, but by only typing a function’s name and pressing enter.

Let’s assume there’s was a point in time I often wanted to know the date, the system drive letter, the current PowerShell host major version, and return a random number between 1 and 20. If I grew tired of doing this manually, I could create a function to do this for me. It’s not likely this would ever be useful outside this post, but it certainly helps highlight what using a function does. It’s essentially four commands in one. Easy.

Function Start-RandomStuff {
    "Date : $(Get-Date)"
    "System Drive : $env:SystemDrive"
    "Host Major Version : $((Get-Host).Version.Major)"
    "Random Number (1-20) : $(Get-Random -Minimum 1 -Maximum 20)"
}
PS > Start-RandomStuff
Date : 02/13/2018 22:58:00
System Drive : C:
Host Major Version : 5
Random Number (1-20) : 3

Think of a function as a wrapper. You can wrap the execution of various (related) commands by running one command. This isn’t to say our example ran related commands so much; it really didn’t. The point is to keep in mind that functions should be single purposed. They’re tight, short, and to the point. If you start wondering if you’re adding too much procedural code to your function, you probably already have. If you keep adding to the function you’re currently writing, then you better be able to explain why.

I’ve done it again! I haven’t really hit those reasons as to why functions, over scripts. Or perhaps I have a little. I do have some specifics topics, and for the second time, let’s hope the next part of this series, gets serious. There really are a few specific things I want to share — reasons why functions are all you want to be writing.

Back soon. And hopefully, with a non winter picture of the cul-de-sac.

Part III is now available.

Write Functions, Not Scripts – Part I

Seriously. If you’re not writing PowerShell functions yet, it’s. time. to. begin. It’s been time.

I’ve decided I should begin to compile some potentially influencing reasons why you’d want make this move. Additionally, I also thought that maybe we need to first, give those out there, that haven’t been doing it, a little push by example. Before we get to some reasons why functions over scripts, do this. Next time you start to write a PowerShell solution, just type what’s been written in the below example.

Function <Verb>-<SingularNoun(s)InPascalCase> {

}

Now, in place of <Verb>, enter an approved verb from the results of the Get-Verb cmdlet. As of today, there’s 98 approved verbs in Windows PowerShell 5.1, and an even 100 in PowerShell 6.0.*

PS > Get-Verb

[/plain]
Verb Group
—- —–
Add Common
Clear Common
Close Common
Copy Common
Enter Common
Exit Common
Find Common
Format Common
Get Common
Hide Common
Join Common
Lock Common

[/plain]

Once you’re done replacing <Verb> with your approved verb, replace <SingularNoun(s)InPascalCase> with a singular noun, or set of singular nouns in pascal case. Here’s some examples: Set-ADDisabledUser, Test-KMSServer, Get-TimeZone, Read-Log, etc. We don’t need plural nouns even if your function is going to run against multiple users, servers, timezones, or logs.

Let’s say you chose Get-TimeZone. Before we actually begin to write timezone related code, let’s make sure our function actually works. Copy and paste the below function to the ISE, or Visual Studio Code, or even the ConsoleHost, and press F8 or Enter (depending on which host you chose). What happens?

Function Get-TimeZone {
    '---->Testing our Get-TimeZone function.<----'
}

Nothing, right? It didn’t even work!

That’s not exactly true. Something did happen. Running the code that makes up a function, doesn’t invoke, or execute, the function. It adds it to memory, or, it adds it to the current PowerShell session. It gets it ready to be run, but how do we know? Let’s check our Function PSDrive. In this example, we’ll see the full process of the function not yet existing, it being created, and then it being available to use.

Here, we’ll verify the function doesn’t yet exist.

Get-Item -Path Function:\Get-TimeZone
Get-Item : Cannot find path 'Function:\Get-TimeZone' because it ...

Here, we’ll add the function to our session/memory.

Function Get-TimeZone {
    '---->Testing our Get-TimeZone function.<----'
}

And here, we’ll verify that it does, now exist.

Get-Item -Path Function:\Get-TimeZone
CommandType     Name                     Version    Source
-----------     ----                     -------    ------
Function        Get-TimeZone

Since it’s now available, let’s try it out.

PS > Get-TimeZone
---->Testing our Get-TimeZone function.<----

A function has a name that we can use to run its included code. The thing is, the code (our function) has to have been defined, or created, before we try and use it. Simple. So, before a function can be used… it must be loaded, or added to memory. Keep all of this in mind.

I want to show one other little secret that’s going to be helpful as you transition to using and writing functions. I know, I know, we were supposed to discuss why you want to use functions, not how to use them. I think it’s important to know a couple things before we really get started, and thus the minor derailment on today’s post. When we get back next time, we’ll immediately jump into the reasons to use functions.

Let’s say we have a file on our Desktop called MyFunctions.ps1. And, let’s say it contains three functions, like this:

Function Test-One {
    'This is the Test One function.'
}
Function Test-Two {
    'This is the Test Two function.'
}
Function Test-Three{
    'This is the Test Three function.'
}

How do we get these functions into our session!? They’re in a file… In a PowerShell host program, perhaps the ConsoleHost, dot source the file as in the below example. You can use either the full path, or navigate to the Desktop first, and just dot source the file by itself (no path). But what’s dot source, right? It’s a dot. Seriously.

PS > Get-Item -Path Function:\Test-One
Get-Item : Cannot find path 'Function:\Test-One' because it ...
PS > . C:\Users\tommymaynard\Desktop\MyFunctions.ps1
PS > Get-Item -Path Function:\Test-One
CommandType     Name                     Version    Source
-----------     ----                     -------    ------
Function        Test-One

[/powershell]
PS > Test-One
This is the Test One function.
PS > Test-Two
This is the Test Two function.
PS > Test-Three
This is the Test Three function.
[/powershell]

Had we not used the full path, we would have had to navigate to the file, and then as mentioned, dot source the file. This below example would also add the three functions to our current PowerShell session.

PS > Set-Location -Path C:\Users\tommymaynard\Desktop
PS > . .\MyFunctions.ps1

Okay, we’re done for today, and again, I’m promise we’ll go into why you want to use functions over scripts… now that you know functions aren’t even scary.

* If you’re curious which two additional approved verbs PowerShell 6.0 has over PowerShell 5.1, then take a look below to find out.

PS > ($PSVersionTable).PSVersion.ToString()
6.0.0
PS > (Get-Verb).Verb | Out-File .\Desktop\6.0Verbs.txt
PS > ($PSVersionTable).PSVersion.ToString()
5.1.14409.1012
PS > (Get-Verb).Verb | Out-File .\Desktop\5.1Verbs.txt
PS > 
PS > $Ref = Get-Content -Path .\Desktop\6.0Verbs.txt
PS > $Dif = Get-Content -Path .\Desktop\5.1Verbs.txt
PS > Compare-Object -ReferenceObject $Ref -DifferenceObject $Dif
InputObject SideIndicator
----------- -------------
Build       <=
Deploy      <=

Part II is now available!

ValidateSet Default Parameter Values

The example code I’m going to include below, I’ve used before. I really like it and so I’m going to give it place here on my website, in case it may ever be helpful for you, and maybe even me again.

The first time I used something like this code example was for a function that created random passwords. By default, that function’s CharacterType parameter would include the four values Lowercase, Number, Symbol, and Uppercase. By using the parameter, you can specify which of the values you actually use, if you didn’t want to use all four. By default, the parameter included them all.

We are defining an advanced function called Test-Function with a single parameter called Type. This parameter uses ValidateSet in order that it’ll only ever accept four different parameter values, for the Type parameter. Additionally, the Type parameter actually includes a default value that includes all four of the values: FullAccess, SendAs, SendOnBehalf, and Calendar. If you ever find yourself needing an All parameter value, just use this option instead; you don’t actually need an All parameter value, you just need to include all the possible values as the default.

After the parameter inclusion, the function begins with a Foreach language construct that will evaluate each Type that been included, whether it’s all four by default, all four because someone use the parameter and entered all four possibilities (not necessary, obviously), or something less than the four options.

Inside each iteration thought the Foreach there’s a Switch statement that will be evaluated. Based on the current type value, its value will be displayed in a string that includes a hard coded value to ensure it’s correct.

Function Test-Function {
    [CmdletBinding()]
    Param (
        [Parameter()]
        [ValidateSet('FullAccess','SendAs','SendOnBehalf','Calendar')]
        [string[]]$Type = ('FullAccess','SendAs','SendOnBehalf','Calendar')
    )

    Foreach ($T in $Type) {
        Switch ($T) {
            'FullAccess' {
                "Doing $T stuff (should match FullAccess)."
            }
            'SendAs' {
                "Doing $T stuff (should match SendAs)."
            }
            'SendOnBehalf' {
                "Doing $T stuff (should match SendOnBehalf)."
            }
            'Calendar' {
                "Doing $T stuff (should match Calendar)."
            }
        } # End Switch.
    } # End Foreach.
}

PS > Test-Function
Doing FullAccess stuff (should match FullAccess).
Doing SendAs stuff (should match SendAs).
Doing SendOnBehalf stuff (should match SendOnBehalf).
Doing Calendar stuff (should match Calendar).

PS > Test-Function -Type 'FullAccess','SendAs','SendOnBehalf','Calendar' # Same as above.
Doing FullAccess stuff (should match FullAccess).
Doing SendAs stuff (should match SendAs).
Doing SendOnBehalf stuff (should match SendOnBehalf).
Doing Calendar stuff (should match Calendar).

PS > Test-Function -Type 'FullAccess','SendAs','SendOnBehalf'
Doing FullAccess stuff (should match FullAccess).
Doing SendAs stuff (should match SendAs).
Doing SendOnBehalf stuff (should match SendOnBehalf).

PS > Test-Function -Type 'FullAccess','SendAs'
Doing FullAccess stuff (should match FullAccess).
Doing SendAs stuff (should match SendAs).

PS > Test-Function -Type 'Calendar','FullAccess','SendAs'
Doing Calendar stuff (should match Calendar).
Doing FullAccess stuff (should match FullAccess).
Doing SendAs stuff (should match SendAs).

PS > Test-Function -Type 'SendOnBehalf','FullAccess','Calendar'
Doing SendOnBehalf stuff (should match SendOnBehalf).
Doing FullAccess stuff (should match FullAccess).
Doing Calendar stuff (should match Calendar).

Nothing down here, but thanks for reading all the way! Actually, here’s a bonus if you didn’t already know it. Those hard coded statements inside the Switch statement, could’ve been written a little differently.

This:

...
            'FullAccess' {
                "Doing $T stuff (should match FullAccess)."
            }
            'SendAs' {
                "Doing $T stuff (should match SendAs)."
            }
            'SendOnBehalf' {
                "Doing $T stuff (should match SendOnBehalf)."
            }
            'Calendar' {
                "Doing $T stuff (should match Calendar)."
            }
...

could’ve actually been this:

...
            'FullAccess' {
                "Doing $T stuff (should match $_)."
            }
            'SendAs' {
                "Doing $T stuff (should match $_)."
            }
            'SendOnBehalf' {
                "Doing $T stuff (should match $_)."
            }
            'Calendar' {
                "Doing $T stuff (should match $_)."
            }
...

Clear Screen After Every Command

Here we go again. I just rescued another draft post, fixed it up enough to share, and published it. Again, this was one of those posts that just never made it past my drafts for one reason or another. I think I figured out what I wasn’t doing correctly, so I’m ready to hand it off.

Never know when I’m going to get inspired to write. Well, I just did and I’m not even sure how it started. All of sudden, I began thinking about ways in which to mess with someone using PowerShell. Perhaps it’s that April Fool’s Day just passed. It’s actually coming, this post is so overdue. I thought to myself, can I get the ConsoleHost to clear each time something is entered? Yeah, of course I can: the prompt function. Been here, done that, just not with such cruel, and obnoxious intentions.

Now to figure it out, for you (and next April Fool’s Day, perhaps). The idea is not to completely modify the prompt function, so as to tip off the user. Instead, the idea is to get their prompt — customized or not — and stuff a Clear-Host command to the end of it. That’s right, every time they enter a command and the prompt is redrawn, it’ll clear the host. Ha! Let’s do this. Yeah, let’s.

How you’re going to get on to your friend’s computer to do this, is up to you. That’s not what I’m here for, just remember your buddy is going to need to spend at least some time in the PowerShell console. Your click-next admin buddies aren’t going to see (or appreciate) this prompt function.

First, we need to get the content that makes up their prompt. It doesn’t matter if it’s been customized or not. Here’s the full command to do that. This command will assign the prompt’s ScriptBlock property to the $CurrentPrompt variable. Additionally, it will pass the value to the ToString() method.

PS MyPrompt > $CurrentPrompt = (Get-Command -Name prompt).ScriptBlock.ToString()

Let’s take a look at the contents of the $CurrentPrompt variable. If you didn’t notice already, you’ll be able to tell that I started with a custom prompt.

PS MyPrompt > $CurrentPrompt
    'PS MyPrompt > '

Next, we’ll create a $NewPrompt variable. Notice that this code includes the $CurrentPrompt variable we created in the first step. This is how we can ensure the prompt has the same look, whether it’s been customized or not. The difference now, is that we’ve added a Clear-Host command inside there. So mean. And Awesome.

PS MyPrompt > $NewPrompt = "$($CurrentPrompt)Clear-Host"

This final command will overwrite the current prompt function with our modification.

Set-Content -Path Function:\prompt -Value $NewPrompt

In closing, I want to provide the full code I used for testing. This contains four different clean prompts, as well as the code we saw above to make the modifications. The first prompt is the one I use on a daily basis and discussed several times around here — it’s my Linux lookalike prompt. Anyway, this will give you some test code to copy to your system and play with. Have fun, then torture your coworkers, but I didn’t say that.

Function Prompt {
	(Get-PSProvider -PSProvider FileSystem).Home = $env:USERPROFILE

	# Determine if Admin and set Symbol variable.
	If ([bool](([System.Security.Principal.WindowsIdentity]::GetCurrent()).Groups -match 'S-1-5-32-544')) {
		$Symbol = '#'
	} Else {
		$Symbol = '$'
	}
	 
	# Write Path to Location Variable as /.../...
	If ($PWD.Path -eq $env:USERPROFILE) {
		$Location = '/~'
	} ElseIf ($PWD.Path -like "*$env:USERPROFILE*") {
		$Location = "/$($PWD.Path -replace ($env:USERPROFILE -replace '\\','\\'),'~' -replace '\\','/')"
	} Else {
		$Location = "$(($PWD.Path -replace '\\','/' -split ':')[-1])"
	}

	# Determine Host for WindowTitle.
	Switch ($Host.Name) {
		'ConsoleHost' {$HostName = 'consolehost'; break}
		'Windows PowerShell ISE Host' {$HostName = 'ise'; break}
        'Visual Studio Code Host' {$HostName = 'vscode'; break}
		default {}
	}

    # Determine PowerShell version.
    $PSVer = "$($PSVersionTable.PSVersion.Major).$($PSVersionTable.PSVersion.Minor)"

	# Create and write Prompt; Write WindowTitle.
    $UserComputer = "$($env:USERNAME.ToLower())@$($env:COMPUTERNAME.ToLower())" 
    $Location = "$((Get-Location).Drive.Name.ToLower())$Location"

    # Check if in the debugger.
    If (Test-Path -Path Variable:/PSDebugContext) {
        $DebugStart = '[DBG]: '
        $DebugEnd = ']'
    }

    # Actual prompt and title.
    $Host.UI.RawUI.WindowTitle = "$HostName $PSver`: $DebugStart[$UserComputer $Location]$DebugEnd$Symbol"
    "$DebugStart[$UserComputer $Location]$DebugEnd$PSVer$Symbol "
}

Function prompt {
    "PS $($executionContext.SessionState.Path.CurrentLocation)$('>' * ($nestedPromptLevel + 1)) "
}

Function prompt {
    'PS > '
}

Function prompt {
    'PS MyPrompt > '
}

Get-ChildItem # Verify no Clear-Host command included.

$CurrentPrompt = (Get-Command -Name prompt).ScriptBlock.ToString()

$CurrentPrompt
	
$NewPrompt = "$($CurrentPrompt)Clear-Host"

Set-Content -Path Function:\prompt -Value $NewPrompt

Get-ChildItem # Verify Clear-Host command included.

PowerShell.org PowerShell Contributors

Have you seen this!?

https://powershell.org/2018/02/01/help-us-recognize-amazing-powershell-contributors/
PowerShell.org has brought back their PowerShell recognition program of the past. This is a great opportunity to say thank you to people in the PowerShell community that may have helped you along your journey. Chances are, that we didn’t all get here entirely on our own. I sure didn’t.

If you’ve been here before and I’ve been able to help you, then let them know. Maybe I did it about you too, because yes, I’ve submitted one name thus far. 🙂 The reward is helping people — I get that, I have since mid 2014 and 200+ posts ago — but recognition across our community is rewarding as well. Let’s lift up and inspire those that contribute, as we help those that want to learn.