0

I've been trying to run Windows PowerShell scripts from a CMD with some parameters.

I've tried things like:

powershell -c ".\Test-Param.ps1 param1 param2"

powershell -c ".\Test-Param.ps1 -P1 param1 -P2 param2"

powershell -File ".\Test-Param.ps1 param1 param2"

This is the code I want to execute:

function Test-Param
{

    [CmdletBinding()] Param(
        [Parameter(Position = 0, Mandatory = $True)]
        [String]
        $P1,

        [Parameter(Position = 1, Mandatory = $True)]
        [String]
        $P2
    )
    echo "Script has been executed!!!"
    echo "Params: $P1,$P2\n"
}

I expect (P1="apple", P2="cherry"):

Script has been executed!!!
Params: apple,cherry
1
  • 2
    The code you posted is a function, but you're invoking a script. A function in a script will not magically invoke itself. Commented Sep 4, 2019 at 12:01

1 Answer 1

1

You must put your parameters at the top of your script, not inside a function.

So your entire .ps1 file should look like this:

    [CmdletBinding()] Param(
        [Parameter(Position = 0, Mandatory = $True)]
        [String]
        $P1,

        [Parameter(Position = 1, Mandatory = $True)]
        [String]
        $P2
    )
    echo "Script has been executed!!!"
    echo "Params: $P1,$P2\n"

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.