Check number of parameters in Powershell script

This topic contains 6 replies, has 3 voices, and was last updated by  Robin16 4 years, 8 months ago.

  • Author
  • #10518



    I'm trying to write a code to check how many parameters ( with positions ) were entered when executing a powershell script.
    For example

    param ( sourceserver,
    when executing a script , if i miss any parameters it should throw an error saying " a parameter is missing " I know we can put a mandatory params but not sure how to achieve what i'm looking for.
    Is it possible to do in powershell ?
    Please let me know
    thanks in advance

  • #10520

    Don Jones

    For example. The shell will prompt for those values rather than throwing an error. If that's not the behavior you want, you'd have to code it yourself.

    if (-not $PSBoundParameters.ContainsKey('sourceserver')) { Write-Error "SourceServer parameter missing" }

    Or something along those lines.

  • #10528


    Thanks Don...i'm aware of these mandatory parameters. If we schedule the PS script as SQL agent job ( including mandatory parameters as you mentioned above )
    and if we miss a parameters and job runs, what will be its behavior ?


  • #10529

    Don Jones

    If it's run under the standard PowerShell host, it'd probably hang waiting for input.

  • #10531

    Dave Wyatt

    If you add the -NonInteractive argument when calling PowerShell.exe to launch your job, you won't have that problem. Any missing mandatory parameters will cause an exception instead of prompting the user for input:

    # Test.ps1:
    param (
        [Parameter(Mandatory = $true)]
    At command prompt:
    C:\Users\Dave\SkyDrive\Source\Temp>powershell.exe -NonInteractive -Command "%cd%\test.ps1"
    C:\Users\Dave\SkyDrive\Source\Temp\test.ps1 : Cannot process command because of one or more missing mandatory parameters: TestParam.
    At line:1 char:1
    + C:\Users\Dave\SkyDrive\Source\Temp\test.ps1
    + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
        + CategoryInfo          : InvalidArgument: (:) [test.ps1], ParameterBindingException
        + FullyQualifiedErrorId : MissingMandatoryParameter,test.ps1
  • #10533

    Don Jones

    Running the job through Agent wouldn't give that option, though. You'd run it as a shell task, so you could specify that.

  • #10540


    Thank you both for the response..
    Hi David, i have tried your suggestion, -NonInteractive. job is running but no never ends.
    One thing i observed ( this is new issue ) is when i run the PS script from powershell console it works fine but when i run it as a sql agent job it fails with some error in code which i dont see when i run it from PS console.

    Don, what do you mean by " run it as a shell task" ?

    Thanks for your valuable responses,time and patience

You must be logged in to reply to this topic.