Examples of Functions

Example1: The following example is a simple function which returns a current date

PS C:\> function Get-DateTime()  

>> {  

>>       return Get-Date  

>> }

Type the following command in the PowerShell console to get the output of above example:

  1. PS C:\> Get-DateTime  

Output:

15 November 2019 14:41:17

Example2: The following example is a function which accepts one parameter and returns a value on that parameter.

PS C:\> function Get-Square([int]$x)  

>> {  

>>   $res = $x * $x  

>>   return $res  

>> }

Type the following command to get the input from a user for the above example:

  1. PS C:\> $x = Read-Host ‘Enter a value’  

Output:

Enter a value: 10

Type the following command to store the return value from the function in a variable which displays the output of function:

PS C:\> $sqres = Get-Square $x  

The following command shows you a result:

PS C:\> Write-Output "$x * $x = $sqres"  

Output:

10 * 10 = 100

Posted

in

by

Tags:

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *