Share via


How to call function in Powershell

Question

Monday, April 20, 2015 9:32 AM

I have this

Switch ($choice) {
"1" { a }
"2" { b }
"3" { c }

function a { ... }

function b { ... }

function c { ... }

when i run it and this error happen, how can i fix it, thank u

a : The term 'a' 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.

All replies (2)

Monday, April 20, 2015 10:24 AM âś…Answered | 1 vote

Hi Nhduy,

in Powershell you must declare a function before calling it. So move your function statements to the top and it should work just fine.

Cheers,
Fred

There's no place like 127.0.0.1


Monday, April 20, 2015 10:18 AM

function switchingpowershell()
{
[int]$Option = 0
while ( $Option -lt 1 -or $Option -gt 5 ){
Write-host "1. Get Computer Services" -ForegroundColor Yellow
Write-host "2. Get BIOS Information" -ForegroundColor Yellow
Write-host "3. Quit and exit" -ForegroundColor Yellow
Write-Host " "
Write-Host " "
  
[Int]$Option = read-host "Please enter an option 1 to 3..." }
Switch( $Option ){
  1{Get-WmiObject -Class Win32_Service
    switchingpowershell}
  2{Get-WmiObject -Class Win32_BIOS
    switchingpowershell}
  3{Write-host "Script Terminated!!!" -ForegroundColor Green
      Break}
}
}
switchingpowershell

http://social.technet.microsoft.com/wiki/contents/articles/23655.windows-powershell-using-switch-choice.aspx

Regards Chen V [MCTS SharePoint 2010]