How to pass the parameters in the PowerShell function?

PowerShellMicrosoft TechnologiesSoftware & Coding

You can pass the parameters in the PowerShell function and to catch those parameters, you need to use the arguments. Generally, when you use variables outside the function, you really don’t need to pass the argument because the variable is itself a Public and can be accessible inside the function. But in some cases we need to pass the parameters to the function and below is the example explains how you can write the code for it.

The single parameter passed in function,

function writeName($str){
   Write-Output "Hi! there .. $str"
}
$name = Read-Host "Enter Name"
writeName($name)

Here, we are passing the $name in the WriteName function and $str variable in the function catches the parameter so, inside the function, you can use $str to retrieve the value.

Output

Enter Name: PowerShell
Hi! there .. PowerShell

For passing multiple values to the function,You can’t use the other programming language method to pass the multiple values to the parameter. Below example is the wrong way,

writeName($name1,$name2)

Instead, in PowerShell, you can use the method mention below to pass the multiple values.

Example

writeName $name1 $name2
function writeName($str1,$str2){
   Write-Output "Hi! there .. $str1 $str2"
}
$name = Read-Host "Enter Name"
$surname = Read-Host "Enter Name"
writeName $name $surname

Output

Enter Name: Harry
Enter Name: Potter
Hi! there .. Harry Potter
raja
Published on 17-Apr-2020 12:35:49
Advertisements