When we have a block of code that will be used over and over again, we should consider putting it into a function. That way, the code block can be reused and managed much more easily than writing the same piece of code multiple times in the script.
Using functions also helps improve code readability and maintainability. With a meaningful function name, we can quickly identify the code and understand what it is supposed to do. If there is a problem in the code, we only have to fix it in one place.
So let’s take a look at some examples of PS Function.
## Example 1
function ShowMyProcess
{
Get-Process
}
ShowMyProcess
Above is a very basic function that shows information about the processes running on my computer. It doesn’t require any parameters.
## Examples 2
function ShowMyFileList ($filepath, [bool]$isRecur)
{
if($isRecur)
{
Get-ChildItem -Path $filepath -Recurse
}
else
{
Get-ChildItem -Path $filepath
}
}
ShowMyFileList "C:\" $true
The second example is a little bit more complex than the first one. The function requires a couple of parameters and it returns results based on the input values. So in the above case, we are expecting the function to list all the files under C drive, in a recursive manner.