Could someone tell me why I can not call a function within a PowerShell script? See below my code:
Write-Host "Before calling Function."
testFunction
function testFunction()
{
Write-Host "Function has been called"
}
When I run the above code I get the following error message:
testFunction : The term 'testFunction' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. At C:\Users\andrew.short\Documents\Powershell\Backups\functionTest.ps1:3 char:1 + testFunction + ~~~~~~~~~~~~ + CategoryInfo : ObjectNotFound: (testFunction:String) [], CommandNotFoundException + FullyQualifiedErrorId : CommandNotFoundException
I'm sure that it must be possible to call functions within the same PowerShell script. Can somebody please help?
A function in PowerShell is declared with the function keyword followed by the function name and then an open and closing curly brace. The code that the function will execute is contained within those curly braces.
When you open PowerShell ISE, you'll be greeted with a console pane. You can open a scripting pane by opening a new file. You can start scripting in this pane. To run the script, click the "Run Script" button on the menu bar.
If you are not able to find your function or you want to call the function then you need to load your . ps1 file which contains the definition of the function; try this command: ". Full path\filename. ps1".
You have to declare the function before using it.
Write-Host "Before calling Function."
function testFunction {
Write-Host "Function has been called"
}
testFunction
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With