SID-500

Home » PowerShell » PowerShell Functions: How to create your first PowerShell Module Command

PowerShell Functions: How to create your first PowerShell Module Command

Easy as can be. It’s not a rocket science to create your first PowerShell command in and save it as a module. Maybe your colleagues will get big eyes when you present them your own solution in form of a function and PowerShell Module. And it’s only the beginning of your PowerShell journey. Let’s do it.

What is a Function?

The official statement is:

A function is a list of Windows PowerShell statements that has a name that you assign. When you run a function, you type the function name. The statements in the list run as if you had typed them at the command prompt.

https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_functions?view=powershell-5.1

I would say: Within a function you can place codes, statements, parameters and so on … This function has a name. And this name is used to start your function.

Here’s an example that can be found in the Microsoft Docs:

function Get-PowerShellProcess {Get-Process PowerShell}

Unbenannt.PNG

After running the function a new command is available: Get-PowerShellProcess. And this command runs Get-Process PowerShell. Fantastic!

In this article we are going to create a funtion and then we’ll save this function as a PowerShell Module. First, let’s do a quick overview what a module is.

What is a PowerShell Module?

module is a set of related Windows PowerShell functionalities, grouped together as a convenient unit (usually saved in a single directory). By defining a set of related script files, assemblies, and related resources as a module, you can reference, load, persist, and share your code much easier than you would otherwise.

https://msdn.microsoft.com/en-us/library/dd878324(v=vs.85).aspx

This means we can load a set of commands into our PowerShell Session. In older Versions of PowerShell you have to manually load modules into your session in order to use the commands of this module. For example – long time ago – you had to import the Module Active Directory to use Active Directory PowerShell commands.

When you run it in Verbose Mode PowerShell presents you all imported commands:

Import-Module ActiveDirectory -Verbose

Unbenannt.PNG

To show all modules that are installed and can be imported run

Get-Module -ListAvailable

Unbenannt.PNG

Modules are stored in a folder.

Default Folder for modules that are shipped with Windows

cd $PSHome\Modules 

18.png

It’s not recommended to save your module here.

Modules Folder for all Users

cd $Env:ProgramFiles\WindowsPowerShell\Modules

18.png

This folder will be used in the next steps.

Modules Folder for the Current User

cd $Home\Documents\WindowsPowerShell\Modules

Functions in Action

Function No. 1: Retrieve the Computer’s IPv4-Address

I have prepared 2 examples to help you get started with the topic.

Let’s dive in. Open Windows PowerShell ISE. (search it or run ise in PowerShell). Copy the following code in your PowerShell ISE Session. We’ll discuss every single item.

function Get-IPv4Address
{Get-NetIPAddress -AddressFamily IPv4 -InterfaceAlias "Ethernet" | Select-Object IPAddress}

function: Defines the start of your work and marks the beginning.

Get-IPv4Address: This the name of your function. This command will be used to execute your code

If you run Get-IPv4Address then

{Get-NetIPAddress -AddressFamily IPv4 -InterfaceAlias “Ethernet” | Select-Object IPAddress}

will be executed. Quite simple.

Press the green icon (run) and next run Get-IPv4Address.

Unbenannt.PNG

Nice. You’ve created your first PowerShell function.

Function No. 2 – Test-Gateway to test the reachability of the Default Gateway of the localhost and on Remote Hosts

Here’s another example. I have to explain this one in more detail. The goal is to test the reachability of the Default Gateway by using the command Test-Gateway. On the local compuer and on remote hosts. The difference to the first example is that I’m now using Parameters and an if – else condition.

function Test-Gateway {
param($Computer = $null,
 $Count = "1")
If ($Computer -eq $null)
{Test-Connection -Destination (Get-NetRoute -DestinationPrefix 0.0.0.0/0 | Select-Object -ExpandProperty Nexthop) -Count $Count}
 else
 {$Route=Invoke-Command -ComputerName $Computer {Get-NetRoute -DestinationPrefix 0.0.0.0/0 | Select-Object -ExpandProperty Nexthop}; Test-Connection -Source $Computer -Destination $Route -Count $Count}
 }

The function’s name is Test-Gateway. Pay attention to the param statement. I provide two parameters: Computer and Count. And I’ve specified standards for this parameters in case of that the user do not provide values for Computer and Count.

If the user doesn’t provide a value for Computer, then this values are $null, so Test-Connection is executed on the localhost. If the user does provide a computer name then the else statement is in action. Then the default gateway of a remote computer is tested. If the user do not provide a Count, then the ping is executed only once. (One ICMP Echo Request)

Why do I call the Default Gateway from Get-NetRoute? Well, the Default Route (0.0.0.0/0) read from the Routing Table always gives me the Default Gateway Address. If you have more than one network card on which can the Gateway Address be found?

Aaaand Action …

First, I do not provide a computername. I’m logged on computer DC01.

Unbenannt.PNG

I now provide a computername. Note, that the remote computer has to reside in the same domain and you usually have to execute the command as a member of the Domain Admins. Client01 can reach it’s Default Gateway.

Unbenannt.PNG

This second example should give you an overview how to create functions with parameters. Let’s go the final step. We want to create a module for this function.

Save your Function as a Script Module

In PowerShell ISE click on File and select Save. To make your function available for all users save it in ProgramFiles\WindowsPowerShell\Modules\Gateway. This means, that you have to create a folder there, which has the same name as your file. Select Type psm1.

1.PNG

Click Save. Close all your PowerShell Sessions. Open PowerShell again and run Get-Module to view your new Script Module.

Get-Module -ListAvailable

Unbenannt.PNG

And here is your new Module and it’s function:

Get-Command -Module Gateway | Format-List

Unbenannt.PNG

Beginning with PowerShell 3.0 your Module is imported automatically, which means that your command is available instantly. No need for importing your module.

Unbenannt.PNG

Conclusion

That’s it for today. Wow. This was the most elaborate article to date. But writing is easier than reading, especially if you are unfamiliar with the subject matter. If you read this, you’ve come to the end and created your first function. Congratulations and respect. Stay close!

See also

To find more out of functions run

Get-Help about_functions

or read one of the great Microsoft Docs:

https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_functions?view=powershell-5.1


1 Comment

  1. […] PowerShell Functions: How to create your first PowerShell Module Command […]

    Like

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

GET-AUTHOR

My name is Patrick Grünauer. Microsoft MVP. I am from Austria. On sid-500 I write about Windows, Cisco and IT-Security in English and German. Have fun while reading!

Categories

Patrick Gruenauer
Follow SID-500 on WordPress.com