Powershell Scripting Fundamentals
Variables
Data types
Casting variables
Automatic variables
Environment variables
Reserved words and language keywords
To learn more about a certain language keyword, you can use Get-Help:
Some reserved words (such as if, for, foreach, and while) have their own help articles. To read them, add about_ as a prefix:
Variable scope
Scope modifier
Using the scope modifier, you can configure the scope in which your variables will be available. Here is an overview of the most commonly used scope modifiers:
global: Sets the scope to global. This scope is effective when PowerShell starts or if you create a new session.
local: This is the current scope. The local scope can be the global scope, the script scope, or any other scope.
script: This scope is only effective within the script that sets this scope. It can be very useful if you want to set a variable only within a module that should not be available after the function was called.
Operators
Arithmetic operators
Comparison operators
Assignment operators
Logical operators
Control structures
A control structure is some kind of programmatic logic that assesses conditions and variables and decides which defined action will be taken if a certain condition is met
If/elseif/else
Switch
Loops and iterations
ForEach-Object
Foreach
while
for
do-until/do-while
break
continue
Naming conventions
Cmdlets and functions both follow the schema verb-noun, such as Get-Help or Stop-Process. So, if you write your own functions or cmdlets, make sure to follow the name guidelines and recommendations.
Finding the approved verbs
PowerShell profiles
PowerShell profiles are configuration files that allow you to personalize your PowerShell environment. These profiles can be used to customize the behavior and environment of PowerShell sessions. They are scripts that are executed when a PowerShell session is started, allowing users to set variables, define functions, create aliases, and more.
All Users, All Hosts ($profile.AllUsersAllHosts): This profile applies to all users for all PowerShell hosts.
All Users, Current Host ($profile.AllUsersCurrentHost): This profile applies to all users for the current PowerShell host.
Current User, All Hosts ($profile.CurrentUserAllHosts): This profile applies to the current user for all PowerShell hosts.
Current User, Current Host ($profile.CurrentUserCurrentHost): This profile applies only to the current user and the current PowerShell host.
To access the file path of one particular profile, such as the one for CurrentUserCurrentHost, you can use the variable that is defined in $profile.CurrentUserCurrentHost:
Use the following code snippet to check whether the file already exists; if it does not yet, the file is created:
Finally, add the commands, functions, or aliases to the user profile:
Understanding PSDrives in PowerShell
PowerShell includes a feature called PowerShell drives (PSDrives). PSDrives in PowerShell are similar to filesystem drives in Windows, but instead of accessing files and folders, you use PSDrives to access a variety of data stores. These data stores can include directories, registry keys, and other data sources, which can be accessed through a consistent and familiar interface.
There are several built-in PSDrives in PowerShell, including the following:
Alias: Provides access to PowerShell aliases
Environment: Provides access to environment variables
Function: Provides access to PowerShell functions
Variable: Provides access to PowerShell variables
Cert: Provides access to certificates in the Windows certificate store
Cert:\CurrentUser: Provides access to certificates in the current user’s certificate store
Cert:\LocalMachine: Provides access to certificates in the local machine’s certificate store
WSMan: Provides access to Windows Remote Management (WinRM) configuration data
C: and D: (and other drive letters): Used to access the filesystem, just like in Windows Explorer
HKCU: Provides access to the HKEY_CURRENT_USER registry hive
HKLM: Provides access to the HKEY_LOCAL_MACHINE registry hive
Making your code reusable
In this section, we will explore the concept of making your code reusable in PowerShell. Reusability is an important aspect of coding that allows you to create a function, cmdlet, or module once and use it multiple times without having to rewrite the same code again and again. Through this, you can save time and effort in the long run.
Cmdlets
A cmdlet (pronounced as commandlet) is a type of PowerShell command that performs a specific task and can be written in C# or in another .NET language.
To find out all cmdlets that are currently installed on the machine you are using, you can leverage Get-Command with the CommandType parameter:
Functions
Once the function is loaded into the session, it needs to be called so that it will be executed:
Parameters
cmdletbinding
cmdletbinding is a feature in PowerShell that allows you to add common parameters (such as -Verbose, -Debug, or -ErrorAction) to your functions and cmdlets without defining them yourself. This can make your code more consistent with other PowerShell commands and easier to use for users.
One way to use cmdletbinding is to declare a parameter as mandatory, positional, or in a parameter set, which can automatically turn your function into a cmdlet with additional common parameters. For example, if you want to make the -Name parameter mandatory in your function, you can add [Parameter(Mandatory)] before the parameter definition, like this:
This will automatically add the [] section to the output of Get-Command, and you will see all the common parameters that are also available in many other cmdlets, such as Verbose, Debug, ErrorAction, and others.
SupportsShouldProcess
If a function makes changes, you can use SupportsShouldProcess to add an additional layer of protection to your function. By adding [CmdletBinding(SupportsShouldProcess)], you can enable the -WhatIf and -Confirm parameters in your function, which help users understand the effect of their actions before executing the function. To use SupportsShouldProcess effectively, you will also need to call ShouldProcess() for each item being processed. Here’s an example of what your code could look like:
With this code, the function can be executed with the -Confirm parameter to prompt the user for confirmation before processing each item, or with the -WhatIf parameter to display a list of changes that would be made without actually processing the items.
Accepting input via the pipeline
It is also possible to configure parameters to accept user input to use it in our code. In addition to accepting input from the user, we can also accept input from the pipeline. This can be done in two ways: by value or by property name.
You can now pass input by value to this function, as shown in the following example:
But it also works to pass input by property name, as the following code snippet demonstrates:
Comment-based help
Writing comment-based help for your functions is crucial; others might reuse your function or if you want to adjust or reuse the function yourself some months after you wrote it, having good comment- based help will simplify the usage:
Error handling
If you are not sure whether your command will succeed, use try and catch:
Aliases
An alias is some kind of a nickname for a PowerShell command, an alternate name. You can set aliases to make your daily work easier – for example, if you are repeatedly working with the same long and complicated command, setting an alias and using it instead will ease your daily work.
To see all available cmdlets that have the word Alias in their name, you can leverage Get-Command:
Next, let’s have a closer look at how to work with aliases, using the Get-Alias, New-Alias, Set-Alias, Export-Alias, and Import-Alias cmdlets.
Get-Alias
To see all aliases that are currently configured on the computer you are working on, use the Get-Alias cmdlet:
New-Alias
You can use New-Alias to create a new alias within the current PowerShell session:
Set-Alias
Set-Alias can be used to either create or change an alias.
So if you want to change, for example, the content of the formerly created Get-Ip alias to Get-NetIPAddress, you would run the following command:
Export-Alias
Export one or more aliases with Export-Alias – either as a .csv file or as a script:
Using this command, we first export all aliases to a .csv file:
The -As Script parameter allows you to execute all currently available aliases as a script that can be executed:
Import-Alias
You can use Import-Alias to import aliases that were exported as .csv:
Import the file to make the alias available in your current session:
Modules
Modules are a collection of PowerShell commands and functions that can be easily shipped and installed on other systems. They are a great way to enrich your sessions with other functionalities.
All modules that are installed on the system can be found in one of the PSModulePath folders, which are part of the Env:\ PSDrive:
Working with modules
To use a module efficiently, the following sections will help you to make the module available, to find out how to work with it, and to finally remove or unload it.
Finding and installing modules
Once you have found the desired module, you can download and install it to your local system using Install-Module:
If you have already installed a module for which a newer version exists, update it with Update- Module:
To see which repositories are available on your system, use the following:
To find out which modules are already available in the current session, you can use Get-Module:
Find out which commands are available by using Get-Command:
And if you want to know more about the usage of a command that is available in a module, you can use Get-Help. You can see how important it is to write proper help pages for your function:
If you have, for example, an old version loaded in your current session and you want to unload it, Remove-Module unloads the current module from your session:
Creating your own modules
When working more intensively with PowerShell modules, you might also come across many different files, such as files that end with .psm1, .psd1, .ps1xml, or .dll, help files, localization files, and many others.
.psm1
The .psm1 file contains the scripting logic that your module should provide. Of course, you can also use it to import other functions within your module.
.psd1 – the module manifest
The .psd1 file is the manifest of your module. If you only create a PowerShell script module, this file is not mandatory, but it allows you to control your module functions and include information about the module.
Creating a basic PowerShell module can be as simple as writing a script containing one or more functions, and saving it with a .psm1 file extension.
First, we define the path where the module should be saved in the $path variable and create the MyModule folder if it does not exist yet. We then use the New-ModuleManifest cmdlet to create a new module manifest file named MyModule.psd1 in the MyModule folder. The -RootModule parameter specifies the name of the PowerShell module file, which is MyModule.psm1.
Using the Set-Content cmdlet, we create the MyModule.psm1 file and define the Invoke- Greeting function, which we wrote earlier in this chapter:
Last updated