0

I have a PowerShell script in which I want to execute a function with the parameters which are provided on the commandline:

Param(
  [string]$param1
  [string]$param2
)

Write-Host $param1

function Run ([string]$param1, [string]$param2){
  New $param1
  New2 $param2
}

function New ([string]$param1){
  Write-Host $param1
}

function new2 ([string]$param2){
  Write-Host $param2
}

Run

But it didn't work. The Run fuction did not get the parameters from which I've provided:

./script.ps1 -$param1="hello" -$param2="hello2"

The Write-Host part outside the functions worked. But the parameters aren't passed to my Run function.

2
  • 1
    How about you run the script yourself instead of asking other people to do it for you? The invocation would be my-script.ps1 -param1 "hello" -param2 "hello2", though. Commented Mar 8, 2017 at 13:53
  • It's more about the approach. Is it the right approach to work like this if you want to provide input paramters to functions Commented Mar 8, 2017 at 13:55

2 Answers 2

2

Your Run function is not working as you expect because you aren't passing the parameters to it.

Update the last line in your script to:

Run -param1 $param1 -param2 $param2

EDIT: The way you are writing and using/linking your functions looks fine. The param names could be a bit more descriptive, but I assume this is example code so this may not be relevant in your actual code.

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

Comments

1

For one thing, the script invocation should look like this:

my-script.ps1 -param1 "hello" -param2 "hello2"

Also, you need to actually pass the script parameters to the Run function. Probably the best way to do this is to splat the automatic variable $PSBoundParameters:

Run @PSBoundParameters

With that said, whether or not to wrap the main script code in a function is more or less a matter of personal opinion and how you intend to use the script.

Con: You need to duplicate the script parameters for the Run function and pass the script arguments.

Pro: It's a bit cleaner, because virtually all code is encapsulated. Also, it allows you to both invoke the script directly and use it as a library if you condionally execute the Run function:

if ($MyInvocation.Line.Split()[0] -ne '.') {
  Run @PSBoundParameters
}

That way you import the functions when dot-sourcing the script, and invoke the Run function with the script parameters when executing the script.

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.