Search code examples
functionpowershellpowershell-3.0

How to pass arguments to functions in PowerShell


I have the below PowerShell script

Function Publish
{
    Param(
        [parameter(Mandatory=$true)]
        [String]
        $RELEASEDIR,

        [parameter(Mandatory=$true)]
        [String]
        $SERVICENAME,

        [parameter(Mandatory=$true)]
        [String]
        $SERVER
    )

    Get-ChildItem "$RELEASEDIR\*"
    $service = Get-Service -Name $SERVICENAME -Computername $SERVER -ErrorAction SilentlyContinue
    $service.Status
}
Publish

How I am executing this:

PS C:\Release\RPCPS> .\RPCPublish.ps1 -RELEASEDIR "C:\Location" -SERVICENAME "value" -SERVER "server"
cmdlet Publish at command pipeline position 1
Supply values for the following parameters:
RELEASEDIR:

Even after passing arguments while executing, the script is expecting it again. What am I doing wrong here?


Solution

  • Your script is creating a function, "Publish", (lines 1-17) and then calling it with no parameters (line 18). Since you've defined parameters as mandatory (lines 4, 7, 10), failing to supply the parameters when you call the function (line 18) causes PowerShell to request values for the unsupplied parameters.

    Supplying parameters to the script file itself does not help; there is no mechanism for "automagically" passing those parameters to anything within the script (you would have to explicitly code the script for that).

    As Matt suggested in the comments, dot-source your script after deleting line 18, and then call your function explicitly, passing the parameters (publish -RELEASEDIR "C:\Release\Batchfile" -SERVICENAME "AmazonSSMAgent" -SERVER "10.0.1.91").