Trying to explore "param"

This topic contains 5 replies, has 4 voices, and was last updated by  Olaf Soyk 1 week, 6 days ago.

  • Author
    Posts
  • #93225

    squigee
    Participant

    This works fine, .\Untitled2.ps1 -Computer hello

    Param(
    [string]$Computer,
    [string]$filepath
    )
    
    "You entered '$Computer' and '$filepath'"
    

    However when I put anything before Param, "param" becomes a unrecognizable command.

    Shouldn't this work below , my aim is trying to Clear-Host before the "Param"

    Clear-Host 
    
    Test
    
    function Test {
        
    Param(
    [string]$Computer,
    [string]$filepath
    )
    
    }
    
    
    "You entered '$Computer' and '$filepath'"
    
    
  • #93228

    Don Jones
    Keymaster

    Param blocks have to be defined before almost anything else. That's the rule.

    But your second example fails because, when you called Test, the function had not yet been defined. PowerShell executes top to bottom.

  • #93229

    Olaf Soyk
    Participant

    I'm curious ...

    ... my aim is trying to Clear-Host before the "Param"

    Why? What for?

  • #93232

    squigee
    Participant

    Im using PowerShell ISE, and I have other stuff in the console previously so I want to clear the screen.

    • #93237

      Olaf Soyk
      Participant

      Hmmm ... if it's because you want to see the output of that particular function without anything before it and you really want it to be hard coded in your function you can place your Clear-Host right after the param block like this:

      function foo{
          Param(
          [string]$Computer,
          [string]$filepath
          )
          Clear-Host
          'some stuff'
          'Some other stuff'
      }
      
      foo
  • #93234

    postanote
    Participant

    ISE, console host, VSCode, etc...

    What you are after is this.
    Use Clear-Host during the call to the function, not before you call the function.

        function Test {
        
        Param(
        [string]$Computer,
        [string]$filepath
        )
    
        }
    
        Clear-Host
        Test 
    
        # Or 
    
        Clear-Host;Test
    

You must be logged in to reply to this topic.