Powershell functions are the most lightweight form of Powershell command, it’s a grouping of code runs against each object defined (within that code) in the script block and performs the specified action. Powershell functions help the administrator to create reusable code which acts as Powershell cmdlets.
Syntax
A function is defined as follows:
function <name>
{<statement list>}
function myfunction { 'Hello world' } Passing arguments to function function myfunction1 { "Hello there $args, how are you?" }
output
PS C:\Windows\System32> myfunction1 raj
Hello there raj, how are you?
function Adition { Param ([int]$var,[int]$var2) $result = $var + $var2 Write-Output $result }
Output:
PS C:\Adition -var 10 -var2 15
25
PowerShell Advanced functions:
The PowerShell advanced functions specified with parameter attribute [cmdletbinding()], this cmdletBinding attribute is similar to the Cmdlet attribute that is used in compiled cmdlet classes to identify the class as a cmdlet.
Example
function Hello-world { [CmdletBinding()] Param( [Parameter(Mandatory=$true)] [string] $Name ) Process { Write-Host ("Hello " + $Name + "!") } }
Output:
PS C:\Windows\System32> Hello-world -Name raj
Hello raj!
Thank you for reading this article, if you have any questions please let us know.
Thank you for visiting my site, for any scripts in these articles you are testing please make sure you have tested this script in our lower environment before you run in production.
Leave a Reply Cancel reply