A function is a segment of code that can be called repeatedly after being declared only once. In the Windows system, functions can also be created inside the PowerShell ISE or within the console. More specifically, the “function” keyword is used to declare a function in PowerShell, which is then followed by the function name that the user assigned. Finally, there are close curly brackets. The added code inside the curly braces gets executed when the function is called in PowerShell.
This post will elaborate on the procedure to call a function within PowerShell.
How to Call a Function Within PowerShell?
These techniques will be employed to call a function:
Method 1: Calling a Function Within PowerShell ISE
PowerShell ISE is the host application of PowerShell. It is employed in the production of scripts and functions. It allows the calling of the specific function within its console. To do so, first and foremost, it is critical to define a function. And then invoke it using its specified name.
Example
This example will demonstrate the calling of the function within PowerShell ISE:
Get-Date -DisplayHint Time
}
currentTime
In this above code:
- First, we have defined a function named “CurrentTime”.
- After that, we called the function by simply writing out its name:
It can be observed that the added function has been successfully invoked, and it displayed the current date on the console.
Method 2: Calling a Function Within PowerShell
The PowerShell console itself also allows the creation and running of the function in its console. Moreover, the created function can be invoked within PowerShell.
Example
Here is the demonstration of defining a function inside the PowerShell:
Write-output "Hello World"
}
Here, the given function will output the added message to the console.
Now, let’s call the function by simply typing its name in the PowerShell terminal:
As you can see, the “text-output” function has been invoked and displayed the added “Hello World” message on the console.
Conclusion
The function in PowerShell can be called inside the PowerShell ISE or PowerShell console itself by simply calling the function name. For that reason, create a function and then invoke it by utilizing its name. On the other way, execute the script to call the function within PowerShell ISE. This post has covered a procedure to fix the mentioned query.