PowerShell you say….?

As this year has progressed and COVID-19 has increasingly changed the way we manage both our home and work lives, I am sure many administrators have found the requirement to use PowerShell to orchestrate their fleet of computers, servers and services more common than ever.

Many companies were forced into pandemic fuelled digital transformation in order to enable their workforce to continue to function. IT Departments will now find a mixture of their servers and services hosted both on-premise and hosted on some flavour of cloud platform; Amazon Web Services, Microsoft O365 / Microsoft Azure or Google Cloud Platform

As a result, fixing everyday issues may now require a few more hoops to jump through before you can just open ‘Active Directory Users & Computers’ and hit “reset password”.

The ability to be able to create your own bespoke tooling to be used for administration of frequently time consuming tasks makes PowerShell the perfect tool for every IT Admin’s arsenal. Everyday user checks can be performed quickly and can be tuned to your own needs or your teams needs.

Back to Top

But PowerShell is painful…

As with any tool, there are a few things you need to configure in order to prevent your experience from being painful and a few tweaks that will make it far easier to use and a much more enjoyable experience. There are also a handful of basic commands that will generally get you out of trouble or help you get on the right track

Execution Policy

The first hurdle most PowerShell users first need to overcome relates to the PowerShell execution policy. PowerShell’s execution policy is a safety feature that controls the conditions under which PowerShell loads configuration files and runs scripts. This feature helps prevent the execution of malicious scripts.

On a Windows computer you can set an execution policy for the local computer, for the current user, or for a particular session. You can also use a Group Policy setting to set execution policies for computers and users.

Execution policies for the local computer and current user are stored in the registry. You don’t need to set execution policies in your PowerShell profile. The execution policy for a particular session is stored only in memory and is lost when the session is closed.

The execution policy isn’t a security system that restricts user actions. For example, users can easily bypass a policy by typing the script contents at the command line when they cannot run a script. Instead, the execution policy helps users to set basic rules and prevents them from violating them unintentionally.

Every user, whether a Local Administrator or not, can change the execution policy to allow them to run scripts as follows:-

# Current User Policy
Set-ExecutionPolicy -ExecutionPolicy Unrestricted -Scope CurrentUser -Force

# Machine Policy - Requires Local Admin rights
Set-ExecutionPolicy -ExecutionPolicy Unrestricted -Force

Without configuring this setting, you will be unable to run any scripts or indeed your PowerShell Profile

Further reading
docs.microsoft.com - Set-ExecutionPolicy
devblogs.microsoft.com - Change PowerShell Script Execution Policy
blog.itpro.tv - SET-EXECUTIONPOLICY
devblogs.microsoft.com - Scripting Guy - Weekend Scripter

Back to Top

PowerShell Profiles?

There are several articles scattered around the internet that already provide either a cursory overview of the PowerShell profiles or a detailed explanation of their functionality. Here are a handful of articles that will no doubt explain anything that I miss.

Further reading
devblogs.microsoft.com - Understanding the Six PowerShell Profiles
docs.microsoft.com - About Profiles
deployhappiness.com - What is the PowerShell Profile and Why Should I Care?
red-gate.com - Persistent PowerShell: The PowerShell Profile

Creating your own Profile

By default your user account will not have any profile files created but it is a simple task to create your own. You can create a blank profile file by copying and pasting the following command:-

if (!(Test-Path -Path $PROFILE)) {
  New-Item -ItemType File -Path $PROFILE -Force
}

Entering the environment variable $PROFILE, will show you the path for your blank profile.

PS C:\> $profile
C:\Users\YOURUSERNAME\Documents\PowerShell\Microsoft.PowerShell_profile.ps1

OK, I have one, now what do I do?

You can very easily edit your profile by entering:-

PS C:\> notepad $PROFILE

Your blank file will open and you can start adding features to your profile.

Back to Top


Example Exchange Functions

If you have an on-premise Exchange Servers, you can copy the following code, replacing http://INTERNAL-EXCHANGE-URI/PowerShell/ with your servers address.

This will enable you to use New-OnPremExchangeSession when you open your profile. No longer requiring you to copy and paste your current strings from your notepad repository of useful commands.

Example Exchange Functions

Back to Top


Example PowerShell Profile

This example adds logic to the profile enabling you to run a particular section of your profile by pressing and holding LeftCtrl/LeftShift/None keys prior to running your PowerShell Session. Selecting one of these options will provide a different set of functions when the Shell starts. This has enabled me to separate Work and Home Functions and also load a session with the noprofile switch from within a single profile.

If you use this example, you will need replacing http://INTERNAL-EXCHANGE-URI/PowerShell/ with your servers address.

Example PowerShell Profile

Back to Top



Example Notes

  • As you can see from these examples, utilising your PowerShell profile can enable you to speed up the process of using your currently saved Functions by placing them in your profile to enable them to auto-load each time you start a New Session.

  • I would recommend that you do not run any code obtained from the internet without understanding what it will do.

Back to Top


Useful Commands

CommandType     Name                  Version    Source
-----------     ----                  -------    ------
Cmdlet          Get-Help              3.0.0.0    Microsoft.PowerShell.Core
Cmdlet          Get-Member            3.1.0.0    Microsoft.PowerShell.Utility
Cmdlet          Get-Command           3.0.0.0    Microsoft.PowerShell.Core
Function        Find-Module           2.2.3      PowerShellGet
Cmdlet          Get-Module            3.0.0.0    Microsoft.PowerShell.Core

There are plenty of different CmdLets, Functions and Modules to play with but there are a handful of commands that will be the most useful. Microsoft recommend that you make very good use of the help function and the PowerSHell founder Jeff Snover, goes so far as to say that you should master this command

Back to Top

Update PowerShell Help

When you first use PowerShell, the local copy of the PowerShell help topics when accessed for the first-time has to be downloaded. It’s recommended to periodically update the help system because there can be updates to the help content from time to time. The Update-Help cmdlet is used to update the help topics. It requires internet access by default and for you to be running PowerShell elevated as an administrator.

Running the folowing commands will download an updated version of the help files.

PS C:\> Update-Help -Force

Back to Top

Get-Help

This is by far my most used command. There are a huge number of commands available in PowerShell and it would be impossible to learn them all. As PowerShell has provided a uniform way to use commands and their switches, using the help for each new command.

Take for example, our old DOS favourite `DIR`
This command has been replaced by Get-Childitem

PS C:\GitRepos> Get-Alias -Name DIR

CommandType     Name
-----------     ----
Alias           dir -> Get-ChildItem

Using Get-Help, you can easily find out how to use the command by looking at examples contained within Get-ChildItem help.

PS C:\> Get-Help Get-ChildItem -Examples

NAME
    Get-ChildItem

SYNOPSIS
    Gets the items and child items in one or more specified locations.


    --- Example 1: Get child items from a file system directory ---

    Get-ChildItem -Path C:\Test

    Directory: C:\Test

    Mode                LastWriteTime         Length Name
    ----                -------------         ------ ----
    d-----        2/15/2019     08:29                Logs
    -a----        2/13/2019     08:55             26 anotherfile.txt
    -a----        2/12/2019     15:40         118014 Command.txt
    -a----         2/1/2019     08:43            183 CreateTestFile.ps1
    -ar---        2/12/2019     14:31             27 ReadOnlyFile.txt

You may just want to view a single parameter.

PS C:\> Get-Help Get-ChildItem -Parameter Directory

-Directory <System.Management.Automation.SwitchParameter>
    To get a list of directories, use the Directory parameter or the Attributes parameter with the Directory property. You can use the Recurse parameter with Directory .

    Required?                    false
    Position?                    named
    Default value                False
    Accept pipeline input?       False
    Accept wildcard characters?  false

Please experiment with Get-Help and read the articles below as your ability to get started with any new commands can only benefit from your practice.

Further reading
Microsoft - The Help System
Microsoft - Get-Help
How To Get More Help with PowerShell Cmdlets
Using the PowerShell Help Command Get-Help

Back to Top

Conclusion

If you have made it to the end of the article, well done, I hope it has been useful. There are many different things that can be achieved with PowerShell, supercharge your PowerShell Session and make those stored functions more useful.

Back to Top