Calling a function within PowerShell ISE

ED209 picture ED209 · Jan 5, 2017 · Viewed 73.6k times · Source

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?

Answer

sodawillow picture sodawillow · Jan 5, 2017

You have to declare the function before using it.

Write-Host "Before calling Function."

function testFunction {
    Write-Host "Function has been called"
}

testFunction