What is Function?
A function is a block of code that has a name and it has a property that it is reusable.
Like in other programming language we can create function in powershell as well, it is basically groups a number of program statements into a unit and function is given name to it.
This unit can be invoked from other parts of a program.
Example
function Addtion ([int] $x, [int] $y) {
$z = $x+ $y
#"Function is running"
return $z
}
#someFunction (5, 4) --Wrong
$b = someFunction 5 4 --right
$b # sum of tow valies
$z # Default value zero here as it is out of scope
Try-Catch-Finally
You can intercept any error in try, catch and finally statements.
PowerShell supports try/catch/finally, that should feel familiar to all java, .Net developers.
PowerShell Version 1 introduced the trap statement that still works; I prefer try/catch/finally.
If you are familar with any other programming language, like other programming languages commands
you should execute should be placed in try block.
$error variable should be written in catch block.
Finally as name suggest, you should do the clean up or release the occupied resourses if any.
Example
try {
Remove-Item "C:\doentexist\file.txt" -ErrorAction Stop
}
catch [System.Management.Automation.ItemNotFoundException] {
Write-Host "item not found" -ForegroundColor red
}
catch {
Write-Host "undefined errors" -ForegroundColor orange
Write-Host $error[0] -ForegroundColor orange
}
finally {
"Finally block"
}
Continue
Function Exit
Function Break
Do While Function Loop
Write function in differnet file and include files /call functions from another file
1. Create psFunctions.ps1 and write some 'XYZ-Function' accepts 2 input parameter (param1, param2) which will return something .
2. Include file calling file in master file.
e.g.