Function is the cool feature of Software programming. Mainly function is used for Code re-using purpose & function syntax is very simple. Here I am trying to explain the Powershell Function but as small as possible for better understanding.


Function Function-Name
 
{
#Your Script
}


Here I am using one command with built-in cmdlet for showing the above syntax.

"Get-ADUser administrator"

Example:-

Function Get-Adminstatus
 
{
#Your Script.
Get-ADUser administrator
 
}

Save that as PS1 & run that but you wont get any output. Then called the function at the Powershell Runspace. Here the function is "Get-Adminstatus". Run that without quote & you will get same output of <Get-ADUser administrator>.

See the below snap for Powershell_ISE



You can put your own code into the script section & that may be huge code & that can be re-usable during the runtime. You don't need to write the same code again. Just you need to call the function if you need same code again.

Also you can create your own Powershell module using Function. As an example use same code but save that as psm1 file. I saved that again "Get-Adminstatus.psm1". After that you need to import that module using the below command.


Import-Module .\Get-Adminstatus.psm1


Use "get-module" for checking the new module.

Now use "GCM -Module Get-Adminstatus" for getting the available commands.

See the below snap from Powershell Run Space.





N.B: Don't use any existing cmdlet/module name.

Help

001
002
003
004
005
help Import-Module -Examples

help about_Functions -Examples

help about_Modules -Examples

See Also