Useful PowerShell functions and snippets

Reading Time: 4 minutes
Useful PowerShell functions and snippets
5 (100%) 2 votes

This post contains a few (short) useful PowerShell functions and snippets, that you can include in projects and/or your profile, and some which showcase some peculiar solutions to problems in PowerShell.

This one is for use in your profile, so you can see in Alt-Tab which Powershell console is running with which user.
I just put this as the first line in the $profile file:

UPDATE: By combining the above line with the Is-Elevated function (shown below), formats and a condition, you can also add information indicating if the PowerShell console is running as administrator (This also shows a way to use a boolean condition to return a conditional string from an array).
Of course, the Is-Elevated function needs to be defined first, so this shows the entire construct:

Some people consider the construction with the array ugly or unreadable.
This is how this construction then works in this example:

This is a simple function to search the English text about_* help files in the documentation in the PowerShell install folder:

A shortcut to view a help article in an external window:

Investigating the methods and the properties of objects:

Get the static methods of the Path object:

Listing the values of all properties of an object:

Getting the full type name of the last exception, so you can use it in a Catch [] statement:

Checking if a script process is running elevated (as Administrator):

For when you cannot remember how to call the garbage collector:

Get a datetime value formatted as a sortable string (Defaults to current time):

Some random Date expressions:

Dynamically convert a hash table containing hash tables to an array of objects:

Excel open workbook example:

Windows registry modification example.
This particular code modifies an item in the registry key for Windows 10’s Update default reboot behavior, so it will not reboot if a user is still logged on (This code was tested with PS version 5.1.14393.206).
The value is not set if the registry key does not exist.

Windows Forms sample/snippet to quickly display a ListBox and two buttons (OK & Cancel) in a modal dialog-style window, and to display the selected choice afterwards: