ICT

[PowerShell]7. Functions

NeoSailer 2023. 4. 3. 16:16

Function in programming lanugage is a reuseable block of code performing set of tasks. With a function in programing language, developer does not need to write the same code every time when executing a certain task, rather simply call a function with parameters then it will do it's magic.

 

[Grammar]

PowerShell function consists of function name, parameters and code block.

function TestFunction{
	param($parameter)
    Write-Host "Hello" $parameter
}

functionName Honey
Hello Honey

 

In the function, "TestFunction" is a function name and "param($parameter)" is the parameter that the fucntion takes as input. in the code block, the function prints out greeting statement with an input. Writing function code itself does not call the function. After writing a function, function name and input should be input to call the function, "functionName Honey"

 

[Parameters]

A function can be build without any parameter

function TestFunction{	
    Write-Host "Hello World!"
}
TestFunction
Hello World!

 

Also with multiple parameters.

function Add{	
    param($firstNumber, $secondNumber)
    $sum = $firstNumber+$secondNumber
    Write-host $firstNumber'+'$secondNumber '=' $sum
}
Add 1 2
1+2 = 3

 

To figure out parameters of function, "Get-Command" in-built function will return number of parameters with parameter type.

Get-Command -Name Add -Syntax
Add [[-firstNumber] <Object>] [[-secondNumber] <Object>]

(Get-Command -Name Add).Parameters.Keys
firstNumber
secondNumber
반응형