DevOps | Scripts | Automation

Powershell

Anatomy of PowerShell Function – II

In the previous article, we have created a small function to check the server uptime. If you have missed reading, please check the article below.

https://theautomationcode.com/anatomy-of-powershell-function-i/

Continuing to the next part, we need this function as reusable code means we can pass the server name and it gives that server last boot uptime.

We can achieve this by adding the parameter using Param block and that contains the variable and its datatype as shown in the below code.

Function Check-LastBootTime{
    param(
        [String]$ComputerName
    )
    Get-CimInstance Win32_OperatingSystem -ComputerName $ComputerName | Select -ExpandProperty LastBootupTime   
}

Once we execute this function, and when you call this function, you can see the ComputerName parameter will popup.

Output:

If there are multiple computers you want to pass then use string array parameter.

Function Check-LastBootTime{
    param(
        [String[]]$ComputerName
    )
    Get-CimInstance Win32_OperatingSystem -ComputerName $ComputerName | Select CSName, LastBootUpTime
}

Output:

There are some commands they don’t accept the multiple-input (i.e. array) in that case you need to use the foreach loop. For example, you can write the above function as shown below.

Function Check-LastBootTime{
    param(
        [String[]]$ComputerName
    )
    foreach($computer in $ComputerName){
        Get-CimInstance Win32_OperatingSystem -ComputerName $Computer | Select CSName, LastBootUpTime    
    }
    
}

I’m sure we are clear up to this. We will see how we can make this parameters mandatory and can add other attributes in the upcoming articles.