0

I am trying to build a script, that accepts named arguments - but the script also has functions in it... This gives me a problem, that I cannot see how to fix. The script - c:\temp\example.ps1 - looks like:

function test
{
 param($p1)
 write-host $p1
}

param(
 [parameter(mandatory=$false)]
 [switch]$EnableOption,
 [parameter(mandatory=$false)]
 [string]$Hostname
)

test -p1 $Hostname

This gives me:

param : The term 'param' 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:\Temp\example.ps1:7 char:1
+ param(
+ ~~~~~
    + CategoryInfo          : ObjectNotFound: (param:String) [], CommandNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException

How do I fix this - so that named parameters can be used for functions - but also be used in the "main" script (getting the command line arguments when calling the script) ?

1 Answer 1

3

Change the order in your script

param(
 [parameter(mandatory=$false)]
 [switch]$EnableOption,
 [parameter(mandatory=$false)]
 [string]$Hostname
)

function test
{
 param($p1)
 write-host $p1
}


test -p1 $Hostname

Param section must be at the start of your code

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.