DevOps | Scripts | Automation

Powershell

Anatomy of PowerShell Function – I

PowerShell function is one of the most useful parts and strong fundamental for creating PowerShell scripts. Functions are useful for getting rid of the repetitive task by calling it as many times as we need so that the code wrapped inside the block is called.

For example, Function created to check the server uptime. We just need to pass the server name as the argument and it gives us the Server uptime every time we call the function.

Syntax:

Function FunctionName(Parameter1,Parameter2,..,ParameterN){
      //Multiple lines of code
}

This is how we can declare the function and to call the function we just need to call by its name.

Below is an example of the function which checks the local computer’s last bootup time.

Function Check-LastBootTime{
    Get-CimInstance Win32_OperatingSystem | Select -ExpandProperty LastBootupTime   
}

Now to execute this function there are two methods.

  • Call function directly from the console after execution.
  • Call it from inside the script.

To call directly from the console, we first need to execute the function so it can be loaded into the PS memory and then call it with its name as shown below.

To call function from the script we just need to use the function name in the script.

Once the function is loaded into memory, we can use it as command.

Get-Command Check-LastBootTime

You can also get help with this function as well. We can add the various sections like Syntax, Aliases, Parameters and that is explained in the latter parts.

We will learn more about PowerShell function in Part-II.

One thought on “Anatomy of PowerShell Function – I

Comments are closed.