Category Archives: Quick Learn

Get the Verbs

So, earlier tonight, my wife, daughter, and me were on the couch. My wife was cleaning out her purse as my daughter helped her organize her change. Me, I was briefly on my phone and looking for a quick list of approved PowerShell verbs. As you likely know, if we create our own cmdlets and functions, we should use an approved verb for the verb, dash, singular noun naming convention: Get-Process, Set-ADUser, Checkpoint-Computer… okay, it’s not always a verb, but you know what I mean.

I couldn’t believe it; I couldn’t just find a simple list of all the verbs, close to one another, and without any explanations. You know the list, the one you basically get when you run Get-Verb. I suppose I should mention that all I had was my phone. There wasn’t a computer close by, and that’s, why I’m putting up a list of the approved verbs (as of PowerShell 5.1 on Windows 8.1), on my website.

Here’s the standard, Get-Verb output that includes the Name and Group. After that, I’ll include the same list, a few more ways. Maybe, just maybe it’ll be here when you, or I, need it next.

PS > Get-Verb

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
Move        Common
New         Common
Open        Common
Optimize    Common
Pop         Common
Push        Common
Redo        Common
Remove      Common
Rename      Common
Reset       Common
Resize      Common
Search      Common
Select      Common
Set         Common
Show        Common
Skip        Common
Split       Common
Step        Common
Switch      Common
Undo        Common
Unlock      Common
Watch       Common
Backup      Data
Checkpoint  Data
Compare     Data
Compress    Data
Convert     Data
ConvertFrom Data
ConvertTo   Data
Dismount    Data
Edit        Data
Expand      Data
Export      Data
Group       Data
Import      Data
Initialize  Data
Limit       Data
Merge       Data
Mount       Data
Out         Data
Publish     Data
Restore     Data
Save        Data
Sync        Data
Unpublish   Data
Update      Data
Approve     Lifecycle
Assert      Lifecycle
Complete    Lifecycle
Confirm     Lifecycle
Deny        Lifecycle
Disable     Lifecycle
Enable      Lifecycle
Install     Lifecycle
Invoke      Lifecycle
Register    Lifecycle
Request     Lifecycle
Restart     Lifecycle
Resume      Lifecycle
Start       Lifecycle
Stop        Lifecycle
Submit      Lifecycle
Suspend     Lifecycle
Uninstall   Lifecycle
Unregister  Lifecycle
Wait        Lifecycle
Debug       Diagnostic
Measure     Diagnostic
Ping        Diagnostic
Repair      Diagnostic
Resolve     Diagnostic
Test        Diagnostic
Trace       Diagnostic
Connect     Communications
Disconnect  Communications
Read        Communications
Receive     Communications
Send        Communications
Write       Communications
Block       Security
Grant       Security
Protect     Security
Revoke      Security
Unblock     Security
Unprotect   Security
Use         Other

As you may have noticed in the previous results, the default output is sorted by the Group. Here comes a second list; however, this list will be sorted by the Verb. I can already see how this may be helpful. In fact, this is the list I was probably after.

PS > Get-Verb | Sort-Object -Property Verb

Verb        Group
----        -----
Add         Common
Approve     Lifecycle
Assert      Lifecycle
Backup      Data
Block       Security
Checkpoint  Data
Clear       Common
Close       Common
Compare     Data
Complete    Lifecycle
Compress    Data
Confirm     Lifecycle
Connect     Communications
Convert     Data
ConvertFrom Data
ConvertTo   Data
Copy        Common
Debug       Diagnostic
Deny        Lifecycle
Disable     Lifecycle
Disconnect  Communications
Dismount    Data
Edit        Data
Enable      Lifecycle
Enter       Common
Exit        Common
Expand      Data
Export      Data
Find        Common
Format      Common
Get         Common
Grant       Security
Group       Data
Hide        Common
Import      Data
Initialize  Data
Install     Lifecycle
Invoke      Lifecycle
Join        Common
Limit       Data
Lock        Common
Measure     Diagnostic
Merge       Data
Mount       Data
Move        Common
New         Common
Open        Common
Optimize    Common
Out         Data
Ping        Diagnostic
Pop         Common
Protect     Security
Publish     Data
Push        Common
Read        Communications
Receive     Communications
Redo        Common
Register    Lifecycle
Remove      Common
Rename      Common
Repair      Diagnostic
Request     Lifecycle
Reset       Common
Resize      Common
Resolve     Diagnostic
Restart     Lifecycle
Restore     Data
Resume      Lifecycle
Revoke      Security
Save        Data
Search      Common
Select      Common
Send        Communications
Set         Common
Show        Common
Skip        Common
Split       Common
Start       Lifecycle
Step        Common
Stop        Lifecycle
Submit      Lifecycle
Suspend     Lifecycle
Switch      Common
Sync        Data
Test        Diagnostic
Trace       Diagnostic
Unblock     Security
Undo        Common
Uninstall   Lifecycle
Unlock      Common
Unprotect   Security
Unpublish   Data
Unregister  Lifecycle
Update      Data
Use         Other
Wait        Lifecycle
Watch       Common
Write       Communications

In this example, all I want to return is the verbs. Nine times out of 10, the group doesn’t make a difference to me.

PS > (Get-Verb | Sort-Object -Property Verb).Verb

Add
Approve
Assert
Backup
Block
Checkpoint
Clear
Close
Compare
Complete
Compress
Confirm
Connect
Convert
ConvertFrom
ConvertTo
Copy
Debug
Deny
Disable
Disconnect
Dismount
Edit
Enable
Enter
Exit
Expand
Export
Find
Format
Get
Grant
Group
Hide
Import
Initialize
Install
Invoke
Join
Limit
Lock
Measure
Merge
Mount
Move
New
Open
Optimize
Out
Ping
Pop
Protect
Publish
Push
Read
Receive
Redo
Register
Remove
Rename
Repair
Request
Reset
Resize
Resolve
Restart
Restore
Resume
Revoke
Save
Search
Select
Send
Set
Show
Skip
Split
Start
Step
Stop
Submit
Suspend
Switch
Sync
Test
Trace
Unblock
Undo
Uninstall
Unlock
Unprotect
Unpublish
Unregister
Update
Use
Wait
Watch
Write

This next example uses Format-Wide so that my results are in columns. Notice how the sorting goes across the rows, as opposed to down the columns. There’s should probably be a built-in way to handle that behavior. Yuck.

PS > Get-Verb | Sort-Object -Property Verb | Format-Wide -Column 4

Add                           Approve                       Assert                        Backup
Block                         Checkpoint                    Clear                         Close
Compare                       Complete                      Compress                      Confirm
Connect                       Convert                       ConvertFrom                   ConvertTo
Copy                          Debug                         Deny                          Disable
Disconnect                    Dismount                      Edit                          Enable
Enter                         Exit                          Expand                        Export
Find                          Format                        Get                           Grant
Group                         Hide                          Import                        Initialize
Install                       Invoke                        Join                          Limit
Lock                          Measure                       Merge                         Mount
Move                          New                           Open                          Optimize
Out                           Ping                          Pop                           Protect
Publish                       Push                          Read                          Receive
Redo                          Register                      Remove                        Rename
Repair                        Request                       Reset                         Resize
Resolve                       Restart                       Restore                       Resume
Revoke                        Save                          Search                        Select
Send                          Set                           Show                          Skip
Split                         Start                         Step                          Stop
Submit                        Suspend                       Switch                        Sync
Test                          Trace                         Unblock                       Undo
Uninstall                     Unlock                        Unprotect                     Unpublish
Unregister                    Update                        Use                           Wait
Watch                         Write

In the next example, I’ll try the -join operator.

PS > (Get-Verb | Sort-Object -Property Verb).Verb -join ', '
Add, Approve, Assert, Backup, Block, Checkpoint, Clear, Close, Compare, Complete, Compress, Confirm, Connect, Convert, C
onvertFrom, ConvertTo, Copy, Debug, Deny, Disable, Disconnect, Dismount, Edit, Enable, Enter, Exit, Expand, Export, Find
, Format, Get, Grant, Group, Hide, Import, Initialize, Install, Invoke, Join, Limit, Lock, Measure, Merge, Mount, Move,
New, Open, Optimize, Out, Ping, Pop, Protect, Publish, Push, Read, Receive, Redo, Register, Remove, Rename, Repair, Requ
est, Reset, Resize, Resolve, Restart, Restore, Resume, Revoke, Save, Search, Select, Send, Set, Show, Skip, Split, Start
, Step, Stop, Submit, Suspend, Switch, Sync, Test, Trace, Unblock, Undo, Uninstall, Unlock, Unprotect, Unpublish, Unregi
ster, Update, Use, Wait, Watch, Write

Also yuck. So yeah, I thought that might turn out better. Well, I’ve got it now — a place to find all the current verbs as of this writing, if I’m ever sitting on the couch, watching two of my favorite people, and unable to decide what verb to use for a new PowerShell tool.

PSMonday #47: March 20, 2017

Topic: Reusable Code V

Notice: This post is a part of the PowerShell Monday series — a group of quick and easy to read mini lessons that briefly cover beginning and intermediate PowerShell topics. As a PowerShell enthusiast, this seemed like a beneficial way to ensure those around me at work were consistently learning new things about Windows PowerShell. At some point, I decided I would share these posts here, as well. Here’s the PowerShell Monday Table of Contents.

I know, I know, I said this would be a four part series, but we’re adding a fifth installment; it’s going to be worth it.

Now that we have a function we want to use whenever it makes sense, we need a place to put it. While we could dot source our Process.ps1 file every time we want to add the function to our scope (like we did last week), there’s two better options. The first option is the profile script. This is a .ps1 file that runs every time you open a new PowerShell ConsoleHost. There’s actually one for the ISE, too.

The below example shows how to determine where the profile script should be located for the current host program (the ConsoleHost).

$PROFILE

C:\Users\tommymaynard\Documents\WindowsPowerShell\Microsoft.PowerShell_profile.ps1

Now, just because we know the path and file, doesn’t mean the file actually exists. The next thing we should do is test the path to determine if the file exists, or not. Test-Path is a helpful cmdlet, in that it can determine if files and folders exist.

Test-Path -Path $PROFILE

False

If you received False when you run the above command, you don’t yet have a profile script. If you do have one, it’ll indicate True. For those with False, let’s quickly create a profile script and then open it.

New-Item -Path $PROFILE -ItemType File -Force

Once this command is run, it’ll indicate that it’s created the profile script file. It’s a simple text file, so it can be opened and edited a number of different ways. As of now, I tend to modify my profile script in the PowerShell ISE. To edit yours in the ISE, use the first below example. To use Notepad, use the second one. For those already using Visual Studio Code, you can open it there as well.

ise $PROFILE

notepad $PROFILE

With your profile script opened, you can add the function we finished with last Monday. It’s included below.

Function Get-TMService {
    Param (
        [Parameter(Mandatory=$true)]
        [string]$Service
    )
 
    try {
        Get-Process -Name $Service -ErrorAction Stop |
            Select-Object -Property @{N='Process Name';E={$_.Name}},
                Description,
                Company,
                @{N='Shared Memory';E={"$([Math]::Round($_.WorkingSet / 1MB)) MB"}},
                @{N='Private Memory Size';
                    E={"$([Math]::Round($_.PrivateMemorySize / 1MB)) MB"}}
    } catch {
        Write-Warning -Message "Cannot locate the $Service process."
    }
}

Now, if you’re following along, enter the below command.

Get-TMService -Service powershell_ise

This command should fail, whether or not, the PowerShell ISE is running. It’s because you added the function to your profile script after the profile script was last run. Close the PowerShell ConsoleHost and then open a new one. Doing this will ensure the recently added function is available in your PowerShell session. At this point, the above Get-TMService command should run successfully.

The second option is to use a PowerShell module. Creating a module can get much more complex, as can most things, but there’s just a few steps to make it work at its simplest form. A module is typically created to hold several related functions; however, it can only hold one function, if that’s all you have for now.

First, copy the above function into a text file, giving it an appropriate name, and saving it as a .psm1 file. For instance, call the new file MyFunctions.psm1 and paste the function code inside of it. Now, create a folder with the same name as the module file (without the file extension). This means your folder would be called MyFunctions. The name of the file and the folder must be the same. Now, move the file into the folder.

Next, we need to relocate this folder to a location in the filesystem where PowerShell will look for modules automatically. You can see those locations using the below example.

$env:PSModulePath -split ';'

C:\Users\tommymaynard\Documents\WindowsPowerShell\Modules
C:\Program Files\WindowsPowerShell\Modules
C:\Windows\system32\WindowsPowerShell\v1.0\Modules\

You’re welcome to use “C:\Program Files\WindowsPowerShell\Modules\” if you want all users on the computer to use the module. If you’re happy with just you being able to use your module, then place it in your profile folder. The final above path, in System32, shouldn’t be bothered if you can help it.

With this completed, the next time you open the PowerShell ConsoleHost you’re module, and that contained function, will be available. If you write some more functions, you can always add them to this same module file, just like you could your profile script.

PSMonday #46: March 13, 2017

Topic: Reusable Code IV

Notice: This post is a part of the PowerShell Monday series — a group of quick and easy to read mini lessons that briefly cover beginning and intermediate PowerShell topics. As a PowerShell enthusiast, this seemed like a beneficial way to ensure those around me at work were consistently learning new things about Windows PowerShell. At some point, I decided I would share these posts here, as well. Here’s the PowerShell Monday Table of Contents.

The below example is the same one we ended on last Monday. What I need you to imagine is that this code now exists in a file called Process.ps1, on the desktop of your own computer. You can even put it there if you want to follow along.

$Service = Read-Host -Prompt 'Enter a Process Name'

try {
    Get-Process -Name $Service -ErrorAction Stop |
        Select-Object -Property @{N='Process Name';E={$_.Name}},
            Description,
            Company,
           @{N='Shared Memory';E={"$([Math]::Round($_.WorkingSet / 1MB)) MB"}},
           @{N='Private Memory Size';
               E={"$([Math]::Round($_.PrivateMemorySize / 1MB)) MB"}}
} catch {
    Write-Warning -Message "Cannot locate the $Service process."
}

In the next example, we’ll begin by changing directories to the desktop. Once there, we’ll run our Process.ps1 file that contains the code we’ve been constructing over the last few weeks. As you’re likely aware, changing directories — the first below command — isn’t necessary, had we simply supplied the full path to the Process.ps1 file in the second command.

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

PS > .\Process.ps1
Enter a Process Name: powershell_ise

Process Name : powershell_ise
Description : Windows PowerShell ISE
Company : Microsoft Corporation
Shared Memory : 181 MB
Private Memory Size : 159 MB

PS > # FYI: Notepad is not currently running.
PS > .\Process.ps1
Enter a Process Name: notepad
WARNING: Cannot locate the notepad process.

After instructing the .ps1 to execute, it immediately prompts us to enter a process name just as we’ve seen in the past. If we enter something that’s running, it returns our modified information according to the command we’ve written. If it’s not running, it displays the Write-Warning message as opposed to throwing the red, and sometimes intimidating, error message we saw last week. What an easy way to return only what you want, and without the need to rewrite the code each time.

Here’s the thing: People love the Read-Host cmdlet, but there’s a better way. Let’s use a Param block instead. This next example does just that. As you move into writing functions, you’ll quickly begin to understand why parameters are better. So you can continue to picture this, we’re saving the below modification over what we had in the Process.ps1 file on the desktop. Watch how we run it now!

Param (
    [string]$Service
)
 
try {
    Get-Process -Name $Service -ErrorAction Stop |
        Select-Object -Property @{N='Process Name';E={$_.Name}},
            Description,
            Company,
            @{N='Shared Memory';E={"$([Math]::Round($_.WorkingSet / 1MB)) MB"}},
            @{N='Private Memory Size';
                E={"$([Math]::Round($_.PrivateMemorySize / 1MB)) MB"}}
} catch {
    Write-Warning -Message "Cannot locate the $Service process."
}
 
PS > .\Process.ps1 -Service notepad
WARNING: Cannot locate the notepad process.
 
PS > .\Process.ps1 -Service powershell_ise
 
 
Process Name        : powershell_ise
Description         : Windows PowerShell ISE
Company             : Microsoft Corporation
Shared Memory       : 178 MB
Private Memory Size : 147 MB

Now, instead of the code using Read-Host to prompt us for input, we have a -Service parameter we can use. When the code was invoked, it took the parameter value we supplied and used it to set the $Service variable. There’s one problem here, however. If we don’t enter the Service parameter, the function will still try and check for a service that wasn’t even included. Let’s make the Service parameter mandatory; we can do that with one quick addition to our code.

Param (
    [Parameter(Mandatory=$true)]
    [string]$Service
)
 
try {
    Get-Process -Name $Service -ErrorAction Stop |
        Select-Object -Property @{N='Process Name';E={$_.Name}},
            Description,
            Company,
            @{N='Shared Memory';E={"$([Math]::Round($_.WorkingSet / 1MB)) MB"}},
            @{N='Private Memory Size';
                E={"$([Math]::Round($_.PrivateMemorySize / 1MB)) MB"}}
} catch {
    Write-Warning -Message "Cannot locate the $Service process."
}

Now, if we forget the Service parameter value, it’ll prompt us to enter it. I had to manually enter “powershell_ise” when it prompted me on the fourth line down, where it says “Service:”.

PS > .\Process.ps1
cmdlet Process.ps1 at command pipeline position 1
Supply values for the following parameters:
Service: powershell_ise
 
 
Process Name        : powershell_ise
Description         : Windows PowerShell ISE
Company             : Microsoft Corporation
Shared Memory       : 188 MB
Private Memory Size : 156 MB

The ultimate goal of someone that really wants to learn PowerShell well, is to lose the whole I-write-scripts mentality, and embrace an I-write-functions mentality. Let’s take our code and make it a function; there’s literally two changes.

We add a new first line that uses the Function keyword. Following that, we give our function a name and add an open, curly brace. Remember as you create functions, to use approved verbs (see Get-Verb for the approved list), a dash, and a singular noun, or singular nouns. You might also add a prefix to the noun, too, such as I’ve done by adding “TM.” This ensures my function won’t take precedence over the Microsoft written and included Get-Service cmdlet (that we actually use inside the Get-TMService function).

Function Get-TMService {
    Param (
        [Parameter(Mandatory=$true)]
        [string]$Service
    )
 
    try {
        Get-Process -Name $Service -ErrorAction Stop |
            Select-Object -Property @{N='Process Name';E={$_.Name}},
                Description,
                Company,
                @{N='Shared Memory';E={"$([Math]::Round($_.WorkingSet / 1MB)) MB"}},
                @{N='Private Memory Size';
                    E={"$([Math]::Round($_.PrivateMemorySize / 1MB)) MB"}}
    } catch {
        Write-Warning -Message "Cannot locate the $Service process."
    }
}

So it’s been said, we’ve again taken the above code and saved it over what we had in Process.ps1. Here’s the trick with using functions that are saved in .ps1 files. To add the Get-TMService function to our PowerShell session, we need to dot source the file. This will make the function available for use. The second below command has a dot and a space before the path and the file name (. .\Process.ps1). That dot is vital, so don’t overlook it. Let’s start by ensuring the function doesn’t yet exist.

PS > Get-Command -Name Get-TMService
Get-Command : The term 'Get-TMService' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again...
 
PS > . .\Process.ps1
 
PS > Get-Command -Name Get-TMService
 
CommandType     Name             Version    Source     
-----------     ----             -------    ------     
Function        Get-TMService
 
 
PS > Get-TMService -Service powershell_ise
 
 
Process Name        : powershell_ise
Description         : Windows PowerShell ISE
Company             : Microsoft Corporation
Shared Memory       : 198 MB
Private Memory Size : 174 MB

Had you read this and the previous three lessons, you’ve seen how we started with a simple command and turned it into a tool that we can use whenever it’s needed. If you give PowerShell some time now, you’re going to get your time back in the future. Until next week.

A Variable’s Current and Previous Value

How to Store a Variable’s Previous Value with the New Value

There was a recent post on the PowerShell Facebook group that said this: “Is there a function or option to check previous $Global:variable -ne Current $Global:variable?” The person that created the post wanted to know if there’s a way to recall the last value a variable stored, once it had already been assigned something new. Here’s my answer, and potential solution.

You have to think about a variable’s previous assignment, as if it never existed, even though you know that variable held something, or was assigned something, previously. Once its value is gone, it’s gone. Now, all that said, I came up with an option. The option, is to use a variable’s description property to store its previous value.

Let’s begin by checking the value of an uninitialized variable, and then assign it something.

PS > $x
PS > # No value.
PS > $x = 'first value'
PS > $x
first value

Now that our variable has a value, let’s take a look at all the variable’s properties using the Get-Variable cmdlet. Notice the Description property; we’re going to use this in a less than conventional way.

PS > Get-Variable -Name x | Select-Object -Property *

Name        : x
Description :
Value       : first value
Visibility  : Public
Module      :
ModuleName  :
Options     : None
Attributes  : {}

Using the Set-Variable cmdlet, we’ll make two modifications to our variable, at nearly the same time. First, we’ll update the Description property, so that it’s holding the original variable assignment (the string ‘first value’). In the same, Set-Variable command, we’ll modify the current value of the variable to the string ‘second value.’ Notice in the final below command, that our Description property has a value now, too.

PS > Set-Variable -Name x -Value 'second value' -Description $x
PS > $x
second value
PS > Get-Variable -Name x | Select-Object -Property *

Name        : x
Description : first value
Value       : second value
Visibility  : Public
Module      :
ModuleName  :
Options     : None
Attributes  : {}

In the next example, you’ll see how we can return the original value and the variable’s updated value. Beneath that, I’ve included a couple ways to compare these values. That gets back to what the person on Facebook was trying to determine. Again, this is fairly unconventional use of the Description property, but it does avoid the need for a second variable to hold the first variable’s original value. That said, one of my examples uses a second, comparison variable.

PS > (Get-Variable -Name x).Description
first value
PS > (Get-Variable -Name x).Value
second value
PS > $x
second value

PS > (Get-Variable -Name x).Description -ne (Get-Variable -Name x).Value
True
PS > (Get-Variable -Name x).Description -ne $x
True
PS > $y = (Get-Variable -Name x).Description
PS > $y -ne $x
True

In these last examples, we’re running into a bit of a problem, we are going to have to keep in mind (if anyone even dares use this approach). When we take a value that isn’t a string, and place it into the Description property, it becomes a string. That means, that when we take it back out, we’ll need to cast it back to its proper type. Take a look at the next series of examples for some assistance with this concept.

PS > $z = 5
PS > Set-Variable -Name z -Value 10 -Description $z
PS > Get-Variable -Name z | Select-Object -Property *

Name        : z
Description : 5
Value       : 10
Visibility  : Public
Module      :
ModuleName  :
Options     : None
Attributes  : {}

PS > (Get-Variable -Name z).Description | Get-Member |
>>> Select-Object -Property TypeName -Unique

TypeName
--------
System.String

PS > [int](Get-Variable -Name z).Description
5
PS > [int](Get-Variable -Name z).Description | Get-Member |
>>> Select-Object -Property TypeName -Unique

TypeName
--------
System.Int32

This goes for decimals values, too. If you use the Description property to store something that’s not a string, then you’re going to have to properly cast it when you’re taking it out, or you’re going to have a string. In these next examples, I used the GetType method to determine the value’s type, as opposed to Get-Member and Select-Object used above.

PS > $m = 2.5
PS > $m.GetType().Name
Double
PS > Set-Variable -Name m -Value 3.5 -Description $m
PS > $m
3.5
PS > $m.GetType().Name
Double
PS > (Get-Variable -Name m).Description
2.5
PS > (Get-Variable -Name m).Description.GetType().Name
String
PS > [double](Get-Variable -Name m).Description
2.5
PS > ([double](Get-Variable -Name m).Description).GetType().Name
Double

And that’s it. It’s may not be the first choice for saving a previous variable’s value, but it’s a choice. I rather liked the array option that was recommended; however, like the $Error array, I’d be tempted to put the newest/current value of a variable into index 0 and not at the end of the array. Anyway, back to real life now.

PSMonday #45: March 6, 2017

Topic: Reusable Code III

Notice: This post is a part of the PowerShell Monday series — a group of quick and easy to read mini lessons that briefly cover beginning and intermediate PowerShell topics. As a PowerShell enthusiast, this seemed like a beneficial way to ensure those around me at work were consistently learning new things about Windows PowerShell. At some point, I decided I would share these posts here, as well. Here’s the PowerShell Monday Table of Contents.

Back again.

We’ve made two new changes to the below code. One, we replaced powershell_ise, inside of our Get-Process command, with $Service. Two, we added a new, first line to our code. This command will prompt the user to enter a value. Read-Host will then assign that value to the $Service variable. That value will be used in the remainder of the PowerShell code every place $Service is found (there’s only the one). Now, the code is no longer only good for checking for the powershell_ise process; it’ll check for whatever process is entered.

$Service = Read-Host -Prompt 'Enter a Process Name'
    Get-Process -Name $Service |
        Select-Object -Property @{N='Process Name';E={$_.Name}},
        Description,
        Company,
        @{N='Shared Memory';E={"$([Math]::Round($_.WorkingSet / 1MB)) MB"}},
        @{N='Private Memory Size';
            E={"$([Math]::Round($_.PrivateMemorySize / 1MB)) MB"}}

If you were to open notepad, you could use this code to return its process information. So let’s do that; let’s say we have notepad open and we run our code.

Enter a Process Name:

Enter a Process Name: notepad

Process Name        : notepad
Description         : Notepad
Company             : Microsoft Corporation
Shared Memory       : 9 MB
Private Memory Size : 1 MB

Our few lines of code just became useable against any running process on the computer. To be as thorough as possible, we need to consider what happens when we enter a process that isn’t actually running — what’s it going to do? Let’s close notepad and find out.

Enter a Process Name: notepad

Get-Process : Cannot find a process with the name "notepad". Verify the process name and call the cmdlet again.
At line:3 char:1
+ Get-Process -Name $Service |
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo          : ObjectNotFound: (notepad:String) [Get-Process], ProcessCommandException
+ FullyQualifiedErrorId : NoProcessFoundForGivenName,Microsoft.PowerShell.Commands.GetProcessCommand

Get-Process doesn’t handle this gracefully, so let’s make a few more changes. We’ll first add a try-catch. The try portion will wrap the Get-Process and Select-Object commands. While it isn’t always necessary, we need to add the ErrorAction parameter name, with the Stop parameter value to Get-Process. This is required in order to prevent this error from being displayed. Forcing a terminating error isn’t always required, so don’t add it to commands when it’s not necessary. You try it without -ErrorAction. If it doesn’t work, you try -ErrorAction SilentlyContinue, and if that doesn’t work, you use -ErrorAction Stop, as we’ve done here.

The catch portion of our try-catch wraps a newly added, Write-Warning command that will gracefully indicate when a process isn’t running, or perhaps, just wasn’t spelled correctly.

$Service = Read-Host -Prompt 'Enter a Process Name'

try {
    Get-Process -Name $Service -ErrorAction Stop |
        Select-Object -Property @{N='Process Name';E={$_.Name}},
            Description,
            Company,
            @{N='Shared Memory';E={"$([Math]::Round($_.WorkingSet / 1MB)) MB"}},
            @{N='Private Memory Size';
                E={"$([Math]::Round($_.PrivateMemorySize / 1MB)) MB"}}
} catch {
    Write-Warning -Message "Cannot locate the $Service process."
}


Here’s what happens now, when you enter a process that isn’t running, or doesn’t even exist.


Enter a Process Name: notepad
WARNING: Cannot locate the notepad process.

Enter a Process Name: asdf
WARNING: Cannot locate the asdf process.

That’s it for this Monday. Keep paying attention; it’s about to get good.

PSMonday #44: February 27, 2017

Topic: Reusable Code II

Notice: This post is a part of the PowerShell Monday series — a group of quick and easy to read mini lessons that briefly cover beginning and intermediate PowerShell topics. As a PowerShell enthusiast, this seemed like a beneficial way to ensure those around me at work were consistently learning new things about Windows PowerShell. At some point, I decided I would share these posts here, as well. Here’s the PowerShell Monday Table of Contents.

In today’s PSMonday, we’ll jump right back into calculated properties, as we continue to create some reusable code. Last week our final addition was to use a calculated property to modify the name of a property, as can be seen below. We took its default value of “Name,” and changed it to “Process Name.”

Get-Process -Name powershell_ise |
    Select-Object -Property @{Name='Process Name';Expression={$_.Name}},Description,Company,WorkingSet,PrivateMemorySize

Today we’ll add two more calculated properties, but before we do, let’s reformat this code a bit, so it fits better. First, we’re going to use “N” instead of Name and “E” instead of Expression, for the keys in our calculated property hash table. Second, we’ll take advantage of the commas between our  properties which allows each of them to sit on their own line. We could have put a space after each comma and left them on the same line as the first property, and it would have wrapped them for us; however, we’re about to add those other calculated properties.

Get-Process -Name powershell_ise |
    Select-Object -Property @{N='Process Name';E={$_.Name}},
        Description,
        Company,
        WorkingSet,
        PrivateMemorySize

The WorkingSet and PrivateMemorySize values are being reported in bytes. Let’s modify that, beginning with the WorkingSet property. Take a look at the newest changes, and we’ll discuss them after the example and its results.

Get-Process -Name powershell_ise |
    Select-Object -Property @{N='Process Name';E={$_.Name}},
        Description,
         Company,
        @{N='Shared Memory';E={"$([Math]::Round($_.WorkingSet / 1MB)) MB"}},
        PrivateMemorySize

Process Name      : powershell_ise
Description       : Windows PowerShell ISE
Company           : Microsoft Corporation
Shared Memory     : 420 MB
PrivateMemorySize : 405536768

As you can see in the above example, we first changed the term “WorkingSet” to “Shared Memory.” This time, however, we also modify the value it displays using the Expression key-value pair. We won’t go into this too deep, other than to say we first, divided our Working Set value by 1 MB, as we wanted to report our values in megabytes. Second, we directly accessed .NET to round our value using a Round method, and finally, we added the string “MB” to the end of the value to make it clear what measurement we’re using.

Next, we’ll add a third calculated property, but this time to the PrivateMemorySize property. This will allow it to function just like the modified WorkingSet property. As you can likely tell, I’ve used more lines than is necessary, in order that this best fits.

Get-Process -Name powershell_ise |
    Select-Object -Property @{N='Process Name';E={$_.Name}},
        Description,
        Company,
        @{N='Shared Memory';E={"$([Math]::Round($_.WorkingSet / 1MB)) MB"}},
        @{N='Private Memory Size';
            E={"$([Math]::Round($_.PrivateMemorySize / 1MB)) MB"}}

Process Name        : powershell_ise
Description         : Windows PowerShell ISE
Company             : Microsoft Corporation
Shared Memory       : 420 MB
Private Memory Size : 387 MB

Okay, let’s stop here and pick up from this point next Monday.

PSMonday #43: February 20, 2017

Topic: Reusable Code I

Notice: This post is a part of the PowerShell Monday series — a group of quick and easy to read mini lessons that briefly cover beginning and intermediate PowerShell topics. As a PowerShell enthusiast, this seemed like a beneficial way to ensure those around me at work were consistently learning new things about Windows PowerShell. At some point, I decided I would share these posts here, as well. Here’s the PowerShell Monday Table of Contents.

After I type the same thing a few times, and suspect I’ll need, or want, to continue to do that, I’ll typically write a function for it, so that I never have to type it again. That’s the purpose of a function. It’s a container for a series of commands that I can run, or invoke, simply by entering its name. Today we’ll start a four-part PSMonday on how to reuse code from beginning to end. As we close up PSMonday, these last several are going to be the ones in which to really pay attention.

Let’s start by entering a simple, Get-Process command, in order to determine whether or not the PowerShell ISE — the PowerShell Integrated Scripting Environment — is currently running.

Get-Process -Name powershell_ise | Select-Object -Property ProcessName,Id

ProcessName      Id
-----------      --
powershell_ise 5732

In the above example, we used Select-Object to filter the properties that are returned by Get-Process. The ISE is running, otherwise we would’ve received an error, indicating that the process could not be found.

Next, let’s pipe the results of an unfiltered, Get-Process command to a mildly modified Get-Member command, and take a look at all the properties of the returned object.

Get-Process -Name powershell_ise | Get-Member -MemberType Property

Here’s another filtered Get-Process command, that only includes the properties that hold information in which I am interested.

Get-Process -Name powershell_ise |
    Select-Object -Property Name,Description,Company,WorkingSet,PrivateMemorySize

Name              : powershell_ise
Description       : Windows PowerShell ISE
Company           : Microsoft Corporation
WorkingSet        : 162627584
PrivateMemorySize : 153522176

Let’s make a change to the Name property using what’s called a calculated property. Among other things, a calculated property allows us to rename a property’s default name to something else.

Get-Process -Name powershell_ise |
    Select-Object -Property @{Name='Process Name';Expression={$_.Name}},Description,Company,WorkingSet,PrivateMemorySize

Process Name      : powershell_ise
Description       : Windows PowerShell ISE
Company           : Microsoft Corporation
WorkingSet        : 162324480
PrivateMemorySize : 153812992

The calculated property looks like this, when it’s all by itself.

@{Name='Process Name';Expression={$_.Name}}

Notice in the above results that Name property is now named, Process Name. The calculated property consists of a hash table, as signified by @{}, that contains two, key-value pairs. One pair includes the Name key, and the second key-value pair includes an Expression key. We’ll continue next week with some additional examples of calculated properties, as we continue to learn about creating reusable code.

PSMonday #42: February 13, 2017

Topic: While

Notice: This post is a part of the PowerShell Monday series — a group of quick and easy to read mini lessons that briefly cover beginning and intermediate PowerShell topics. As a PowerShell enthusiast, this seemed like a beneficial way to ensure those around me at work were consistently learning new things about Windows PowerShell. At some point, I decided I would share these posts here, as well. Here’s the PowerShell Monday Table of Contents.

The last language construct we’re going to discuss is the While loop — yes, another looping construct. Let’s start with the help file in the first below command, followed by two ways to write the conceptual structure of the While loop.

Get-Help -Name about_While -ShowWindow

While (<condition>){<statement list>}

While (<condition>) {
     <statement list>
}

Our first below example of the While loop, well, it does absolutely nothing. We begin by setting our $Value variable to the numeric value of 1, and then we (attempt) to enter the While loop. The biggest difference between the While loop and the Do loop is that our conditions come before the statement lists. This should be reminiscent of the If, and Switch statement variations, where the evaluations come first.

$Value = 1

While ($Value -eq 5) {
    $Value
    $Value = $Value + 1
}

In the next example, we’ll make one simple change and the code will run. Our condition will evaluate the $Value variable such that it’s $true when $Value is less than or equal to 5. Remember from the For loop, that $Value++ is the same as writing $Value = $Value + 1.

$Value = 1

While ($Value -le 5) {
    $Value
    $Value++
}

1
2
3
4
5

Our final example for the While loop, gives the user an opportunity to try and guess a number between one and five. Before we potentially, enter the While construct, we’ll set the $MagicNumber variable to the random number and the $Continue variable to $true. We enter the While providing that $Continue is equal to $true, and we know it will be, as it was just assigned that value.

Inside the statement list, we (1) request the user enter a number between one and five, and (2) use and If-Else to see if the $MagicNumber matches the guess entered by the user, as stored in $Guess. If it matches, we indicate that, and then set $Continue to $false. This means that the next time the While begins, the condition won’t match and we won’t enter the While. The loop will be over. If $Guess and $MagicNumber don’t match, the While will execute again, and we’ll ask for another number.

$MagicNumber = Get-Random -Minimum 1 -Maximum 5
$Continue = $true

While ($Continue -eq $true) {
    $Guess = Read-Host "Enter the magic number"
    If ($Guess -eq $MagicNumber) {
        "You guessed it: $Guess <--> $MagicNumber"
        $Continue = $false

    } Else {
        Write-Output -InputObject 'Try again.'
    }
}

Enter the magic number: 5
Try again.
Enter the magic number: 4
Try again.
Enter the magic number: 2
Try again.
Enter the magic number: 3
You guessed it: 3 <--> 3

And, that’s it. We’ve seen and learned everything from If to Switch and For to While. As it was stated previously, knowing which language construct to use should be left to your intuition, and a full understanding of a language’s conditional options is the only way that’s going to happen. Next week we’ll start discussing reusable code.

Sync Profile Script from Work to Home

After a few years of this whole I-do-PowerShell-everyday thing, my profile script has become quite the necessity at both work, and home. In fact, there’s much in my work profile script that I want at home, such as my prompt function, among others. With this ever present need, I set off to create a profile script that self-updates between my work and home computer, without any continuing need for me to do it myself.

So, about the profile script, just in case you ended up here and are clueless to that in which I’m referring. There’s a potential .ps1 file that can be created and edited so that every time you open the PowerShell ConsoleHost things run in the background, as the session begins. I use it to initialize variables, to create aliases, to declare functions, and more. In regard to Profiles, here’s an old Scripting Guy article that may be of help if you need it. I may have started there myself a few years ago.

I’ve broken the structure of my profile script template into three logical parts. Have a look at the first section of the template below, and then we’ll discuss it.

$WorkComputer = 'WorkComputer'
$HomeComputer = 'HomeComputer'

Switch ($env:COMPUTERNAME) {

    # Work computer only.
    {$_ -eq $WorkComputer} {

    } # End work computer only.

    # Home computer only.
    {$_ -eq $HomeComputer} {

    } # End home computer only.

    # Work and home computer.
    {$_ -eq $WorkComputer -or $_ -eq $HomeComputer} {
 
    } # End Work and home computer.
} # End Switch.

In lines 1 and 2, we create two variables, $WorkComputer and $HomeComputer. As you might expect, these variables store the computer names of my work, and my home computers. If you choose to use this template, then these variable assignments will require a small bit of manual editing on your own; however, it’s a one time thing, and in my mind, a small price to pay to have your profile synced between two computers.

Following these two variable assignments, is the above Switch statement. This defines what will be available on the two different computers. The first section in the Switch are things I only want available on my work computer, the second section are things I only want available on my home computer only, and the last section is for things that I want available on both my work and home computer. This last section is where I placed my prompt function, for instance, in order that it’s available regardless of where I’m working. I really don’t want to be without it.

At the end of this post, I’ll included the full, uninterrupted code, but for now, let’s have a look at the next section. This section defines the Sync-ProfileScript function.

# Create Sync profile function.
Function Sync-ProfileScript {
    [CmdletBinding()]
    Param (
        [Parameter(Mandatory=$true)]
        [ValidateSet('Source','Destination')]
        [string]$ComputerType,

        [Parameter()]
        [string]$LocalProfileScriptPath = "$env:USERPROFILE\Dropbox\PowerShell\Profile\Microsoft.PowerShell_profile.ps1"
    )

    Begin {
        # Exit if NOT the ConsoleHost.
        If (-Not($Host.Name -eq 'ConsoleHost')) {
            break
        }
    } # End Begin.

    Process {
        If (Test-Path -Path $PROFILE) {
            $CompareFiles = Compare-Object -ReferenceObject (Get-Item $PROFILE).LastWriteTime -DifferenceObject (Get-Item $LocalProfileScriptPath).LastWriteTime -IncludeEqual |
                Select-Object -First 1

            If ([System.Boolean]($CompareFiles.SideIndicator -ne '==')) {

                Switch ($ComputerType) {
                    'Source' {Copy-Item -Path $PROFILE -Destination $LocalProfileScriptPath}

                    'Destination' {
                        Copy-Item -Path $LocalProfileScriptPath -Destination $PROFILE

                        'Profile Script has been updated. Restart ConsoleHost?'
                        Do {
                            $Prompt = Read-Host -Prompt 'Enter r to Restart or c to Cancel'
                        } Until ($Prompt -eq 'r' -or $Prompt -eq 'c')

                        If ($Prompt -eq 'r') {
                            Start-Process -FilePath powershell.exe
                            Stop-Process -Id $PID
                        }
                    }
                } # End Switch.
            } # End If.
        } # End If.
    } # End Process.

    End {
    } # End End.
} # End Function: Sync-ProfileScript.

The purpose of the Sync-ProfileScript function is to copy the profile script to a Dropbox folder, when the ConsoleHost is opened on the work computer. Additionally, it serves to copy the profile script from that same Dropbox folder, when the ConsoleHost is opened on the home computer. Keep in mind that I’ve purposely written this function to always go from the work computer, to the home computer. I don’t plan to make changes in the profile script on the home computer, that I’ll then expect or want, on the work computer.

Let’s cover what’s happening in this function. In lines 1 – 11 we define out Sync-ProfileScript function with two parameters: ComputerType and LocalProfileScriptPath. We use the ComputerType parameter to indicate whether this is the source or destination computer. Source is work and destination is home. The LocalProfileScriptPath parameter points to the profile script (.ps1 file), located in Dropbox. As it has a default value, I don’t have to send in a parameter value when the function is invoked.

Our Begin block serves one quick purpose and that’s to exit the function immediately, if we’re not in the ConsoleHost, and instead inside a host such as the ISE. The magic happens in the Process block. Here’s what we do, in order: (1) Test to see that there’s an actual profile script being used, (2) if there is, compare the LastWriteTime on the profile script file used by the ConsoleHost ($PROFILE), and the file in Dropbox, (3) if they are different, either copy the profile script used by the ConsoleHost to Dropbox, or copy the profile script in Dropbox to the location used by the ConsoleHost. Again, this is dependent on which computer we’re using: work or home.

Let’s stop and consider something from the perspective of the home computer. If I open the PowerShell ConsoleHost there, it’ll potentially download the newest version of the profile script from Dropbox to its place on the filesystem. Great. The problem is that any changes to the profile script won’t be usable until the next time that ConsoleHost is started. I think I could’ve run & $PROFILE, but I skipped that option as I vaguely remember that it didn’t always work for me.

Therefore, I added a bit more code. If the home computer notices a change to the profile script, it’ll indicate that to the user by writing “Profile Script has been updated. Restart ConsoleHost?” and “Enter r to Restart or c to Cancel.” If the user enters “r,” it’ll restart the ConsoleHost loading the newest version of the profile script by default. If the user enters “c,” it’ll cancel the ConsoleHost restart and the newest version of the profile script will not be updated on the home computer. It will, however, be updated the next time a ConsoleHost is opened.

Now, on to the final portion of my profile script. Don’t worry, this part is less involved than the Sync-ProfileScript function.

# Determine if sync counter variable exists.
If (-Not($env:SyncProfileCounter)) {
    $env:SyncProfileCounter = 0

    # Copy profile script to/from Dropbox by calling Sync-ProfileScript.
    If ($env:COMPUTERNAME -eq $WorkComputer) {
        Sync-ProfileScript -ComputerType Source

    } ElseIf ($env:COMPUTERNAME -eq $HomeComputer) {
        Sync-ProfileScript -ComputerType Destination
    } # End If-ElseIf.
} # End If.

This section of the profile script invokes the Sync-ProfileScript function we discussed in the last section. If it’s run on the work computer, it indicates to the Sync-ProfileScript function to copy the profile script to Dropbox. If it’s run on the home computer, it indicates to the function to copy the profile script from Dropbox. We know this already, however. It uses a counter variable stored inside an environmental variable to ensure this If statement doesn’t perpetually run, and therefore perpetually call the Sync-ProfileScript function. I won’t a separate post about that here.

I realize that not everyone is using Dropbox. If you’re using another service, then I highly suspect you can use what you’ve learned here, with them as well. You’ll just need to determine the local path to use, and adjust your profile script accordingly. If someone wants to let me know about OneDrive, that would be great. I’d be more than happy to include that information in this post!

Here’s the complete profile script template. Thanks for your time.

$WorkComputer = 'WorkComputer'
$HomeComputer = 'HomeComputer'

Switch ($env:COMPUTERNAME) {

    # Work computer only.
    {$_ -eq $WorkComputer} {

    } # End work computer only.

    # Home computer only.
    {$_ -eq $HomeComputer} {

    } # End home computer only.

    # Work and home computer.
    {$_ -eq $WorkComputer -or $_ -eq $HomeComputer} {
 
    } # End Work and home computer.
} # End Switch.

# Create Sync profile function.
Function Sync-ProfileScript {
    [CmdletBinding()]
    Param (
        [Parameter(Mandatory=$true)]
        [ValidateSet('Source','Destination')]
        [string]$ComputerType,

        [Parameter()]
        [string]$LocalProfileScriptPath = "$env:USERPROFILE\Dropbox\PowerShell\Profile\Microsoft.PowerShell_profile.ps1"
    )

    Begin {
        # Exit if NOT the ConsoleHost.
        If (-Not($Host.Name -eq 'ConsoleHost')) {
            break
        }
    } # End Begin.

    Process {
        If (Test-Path -Path $PROFILE) {
            $CompareFiles = Compare-Object -ReferenceObject (Get-Item $PROFILE).LastWriteTime -DifferenceObject (Get-Item $LocalProfileScriptPath).LastWriteTime -IncludeEqual |
                Select-Object -First 1

            If ([System.Boolean]($CompareFiles.SideIndicator -ne '==')) {

                Switch ($ComputerType) {
                    'Source' {Copy-Item -Path $PROFILE -Destination $LocalProfileScriptPath}

                    'Destination' {
                        Copy-Item -Path $LocalProfileScriptPath -Destination $PROFILE

                        'Profile Script has been updated. Restart ConsoleHost?'
                        Do {
                            $Prompt = Read-Host -Prompt 'Enter r to Restart or c to Cancel'
                        } Until ($Prompt -eq 'r' -or $Prompt -eq 'c')

                        If ($Prompt -eq 'r') {
                            Start-Process -FilePath powershell.exe
                            Stop-Process -Id $PID
                        }
                    }
                } # End Switch.
            } # End If.
        } # End If.
    } # End Process.

    End {
    } # End End.
} # End Function: Sync-ProfileScript.

# Determine if sync counter variable exists.
If (-Not($env:SyncProfileCounter)) {
    $env:SyncProfileCounter = 0

    # Copy profile script to/from Dropbox by calling Sync-ProfileScript.
    If ($env:COMPUTERNAME -eq $WorkComputer) {
        Sync-ProfileScript -ComputerType Source

    } ElseIf ($env:COMPUTERNAME -eq $HomeComputer) {
        Sync-ProfileScript -ComputerType Destination
    } # End If-ElseIf.
} # End If.

TechNet Wiki Link:
https://social.technet.microsoft.com/wiki/contents/articles/37104.powershell-sync-profile-script-from-work-to-home.aspx

February 2017 Guru Link:
https://social.technet.microsoft.com/wiki/contents/articles/36936.technet-guru-competitions-february-2017.aspx

Three Ways to Set $PSDefaultParameterValues

Although we’ve discussed the $PSDefaultParameterValues before, I wanted to a do a quick recap. I need one place that shows the various ways to set this variable. That’s what this post will do for me, and perhaps you too.

First, however, let’s remind everyone what the $PSDefaultParameterValues variable does for us. It allows us to set a custom, default value for a function, or cmdlet’s parameter. One of the examples I mentioned before, in one of the three posts I’ve written about $PSDefaultParameterValues (1 | 2 | 3), used Get-Help.

This cmdlet includes a ShowWindow switch parameter that will open the full help inside its own GUI window. I tend to use this option a great deal to keep my ConsoleHost clean. In order to keep this post short, I’m just going to write the three ways in which I’m aware that we can set this variable.

$PSDefaultParameterValues.Add('Get-Help:ShowWindow',$true)

$PSDefaultParameterValues = @{'Get-Help:ShowWindow' = $true}

$PSDefaultParameterValues['Get-Help:ShowWindow'] = $true

Oh, Lee Holmes posted a welcome PSDefaultParameterValues addition on Twitter recently. I’ve included that addition below using the three above options, as well. Unlike his example, I moved from three underscores, to two. You’ll see what I mean below, if you haven’t already read the Tweet. With this example in place, the results of all the commands entered will end up in the $__ variable. Again, that’s two underscores. Run a Get-ADUser command, for instance, and you’ll get the results both on the screen, and in the $__ variable up until you run another command that can make use of the OutVariable common parameter.

$PSDefaultParameterValues.Add('Out-Default:OutVariable','__')

$PSDefaultParameterValues = @{'Out-Default:OutVariable' = '__'}

$PSDefaultParameterValues['Out-Default:OutVariable'] = '__'