Powershell Custom Function - Best approach with Params?

Fellow Powershellers.
I want to build a custom function. My question is about parameters. I have read many of the online doco’s and examples. I see some that have Params with names and not defining type - which is fine by me. I see others that do not use params but just create the function wiht (item1, item2) etc.
Is there a preference?

Example 1 (with param)

function Insert_ExcelRows {
Param($results, $myWorkShet, $IN_AutoFit)


}

Calling it as:

Insert_ExcelRows -results $results -myworksheet $myWorkSheet -In_Autofit $IN_AutoFit

Example 2 (without param):
function Insert_ExcelRows ($results, $myWorkSheet, $IN_AutoFit )
{


}

Calling it as:
Insert_ExcelRows $results $myWorkSheet $IN_AutoFit

Is there one that is preferred?

thx

MG

I’d say that’s a matter of personal or company preference. When your company does not require a certain type of code style it is up to you. :wink:

I prefer the most verbose style for functions because I think they are the easiest to read and to understand.

I like to use the snippet VSCode offers when you start typing “funct …”. The result is this:

function Verb-Noun {
    [CmdletBinding()]
    param (
        
    )
    
    begin {
        
    }
    
    process {
        
    }
    
    end {
        
    }
}

And I also try to be very verbose with the single parameters …

Param(
    [Parameter(Mandatory=$true,
    ValueFromPipeline=$true)]
    [string[]]
    $ComputerName
)

Hi Olaf,

Thanks for that. I have tested it both ways with what I had in the original email and results appear to be the same. So, it is my interpretation that when you define a parameter wihtout indicating a datatype, it inherits that from the source. Is that correct?

thx
MG

Yes. :wink: That’s the case for all variables in PowerShell. For example:

$Integer = 15
$Float = 3.1415926
$String = 'bla'
$Bool = $true

$Integer.GetType()
$Float.GetType()
$String.GetType()
$Bool.GetType()

Thx for the confirmation Olaf
MG