Hey There!!!
Today we are going to learn, How to write a Powershell function which takes a parameter.
Before that, you can read my article, Write Your first Powershell barebone function
If you want to watch it on video, then you can watch my youtube video on the same topic.
[embed]https://youtu.be/U0qd9um3ws4[/embed]
Ok. let us start.
We first need to tell Powershell terminal that we want to create a function, for that we use function keyword.
example :- function Print-FullName
And that's we are telling the Terminal that, we want to create a function named Print-FullName ...
And, to make this function useful, we have to provide the logic, which the terminal will execute.
We provide that logic in curly braces, open and close.
example :- { Write-Output "My FullName is Anurag Anand"; }
So, when we put all these together, we get
function Print-FullName {
Write-Output "My FullName is Anurag Anand";
}
So, when I call this function, It is going to print My FullName is Anurag Anand.
Like shown in the screenshot
But, you see here the problem is, the text printed by Write-Output function always prints the same string/text, and we have no way of
changing that. But, that can be changed if we allowed the function to take arguments, and for that we have to define parameters.
Example :
function Print-FullName {
param([string]$FullName)
Write-Output "My FullName is $FullName"
}
We have added an extra line param([string]$FullName) .
Inside the param keyword we define the parameters.
- [string] is the datatype
- $FullName is the variable name.
- And, we use the vairable, $FullName, in the string/text
We can have more than one parameters, but, here we have only defined one.
In Powershell, If a string is contained inside double-quotes, then variables are replaced by their values.
So, $FullName is replaced by whatever value passed during function call.
Example :-
There are two ways to call this function.
First, we can provide the name of the parameter.
PS D:\> Print-FullName -FullName "Anurag Anand"
Second, as there are only one parameter, then we do not need to provide the parameter name.
So, we can just write the value and it will work.
PS D:\> Print-FullName "Anurag Anand"
Here, I am passing "Anurag Anand", as the value of $FullName
Here is the screenshot of multiple executions.
I am using both ways, where we pass the parameter name and without parameter name.
So, this concludes this blog.
Thank you - Anurag Anand