Detecting param variable input only

This topic contains 3 replies, has 3 voices, and was last updated by Profile photo of Rob Simmers Rob Simmers 2 years, 5 months ago.

  • Author
    Posts
  • #16298
    Profile photo of Adam Bertram
    Adam Bertram
    Participant

    I have a script with a standard string param in it. In the script, I want to detect if this string is $null. I've included a script snippet. Rather than using 2 variables, is it possible to set a condition only on the parameter? Something like setting a type of [param] like if ([param]$x) ?

    param($x)
    
    $somearray = 'product1','product2'
    
    foreach ($element in $somearray) {
        ## I only want to test against the $x set by the param
        ## I don't want this if $x was set lower in the script
        if (!$x) {
           do something
        }
        ......
        .......
        $x = 'something'
    }
    
  • #16299
    Profile photo of Adam Bertram
    Adam Bertram
    Participant

    Nevermind. Posted too soon. $PSBoundParameters['x'] did the trick.

  • #16300
    Profile photo of Dave Wyatt
    Dave Wyatt
    Moderator

    It's not really a good practice to overwrite the value of a parameter variable like that. Technically, though, you could check the value of $PSBoundParameters['x'] to get at the original argument that was passed in. Personally, I would just use two variable names, even if one is originally initialized as a copy of $x.

  • #16301
    Profile photo of Rob Simmers
    Rob Simmers
    Participant

    Take a look at advanced functions: http://technet.microsoft.com/en-us/library/hh847743.aspx

        Param
              (
                [parameter(Mandatory=$true)]
                [ValidateNotNull()]
                $x
              ) 
    

You must be logged in to reply to this topic.