PowerShell functions with parameters like in C#

10 Sep 2021

Sometimes we do love PowerShell for its flexibility, but every so often we don’t. During this (really) small article we would learn how to create PowerShell function and pass parameters to it.

You may ask “Hey, what can be wrong here? I just want to write a simple function like I do in C#. Just several function parameters I can work with.”

Well, in some cases everything goes wrong. Let’s figure it out a little.

What if

What if you want to create a simple function with parameters?

In C# language, you’d write something similar to this

1void MyFunction(string message) 2{ 3 System.Diagnostics.Debug.WriteLine($"MyFunction: {message}"); 4} 5MyFunction("Hello"); // call the function

And to execute the function, you simply do MyFunction("Hello").

That was simple, hah?

In PowerShell you can do the same this way:

1function My-Function($Message) { 2 Write-Host "My-Function: $Message" 3} 4My-Function("Hello") # call the function 5# or 6My-Function "Hello again" 7# or 8My-Function -Message "And once again"

Well. PowerShell gives you an ability to call the function in several ways.

But what to do if you want to make function parameter strictly typed? Then you have to use an additional block of code — [Parameter()]. (That looks like an attribute in C#) and the next version of our sample will be:

1function My-Function() { 2 param([Parameter()] [string] $Message) 3 4 Write-Host "My-Function: $Message" 5} 6 7# I left only one function call example here 8My-Function "Hello"

Both examples look probably the same, except for a strange parameter declaration inside the param section. This one — [Parameter()] [string] $Message. It seems too much exceeded characters to create a typed parameter for the function, but it is how it works.

[Parameter()] [string] $Message says, “Hey, I want a Message parameter of type string”. And PowerShell does it. Moreover, you can create as many parameters as you wish:

1param( 2 [Parameter()] [string] $FirstName, 3 [Parameter()] [string] $Address, 4 [Parameter()] [int] $Age 5)

What about required parameters?

What to do if you want to make one of parameters required?

The answer is simple — use Mandatory keyword:

1[Parameter(Mandatory)] [string] $Name

That’s all for this post.

Try PowerShell by your own — it is way more powerful that it looks like at first.