PowerTip: Don’t Name a Variable $input

PowerTip: Don’t Name a Variable $input

  • Comments 5
  • Likes

Summary: Advice against using $input for a variable name.

Hey, Scripting Guy! Question Can I use a variable named $input to hold input from the Read-Host cmdlet?

Hey, Scripting Guy! Answer $input is an automatic variable that is used for script blocks in the middle of a pipeline.

As such, it would be a very poor choice. 

Call the variable something like $userInput if you wish; but please do not call it $input

Your comment has been posted.   Close
Thank you, your comment requires moderation so it may take a while to appear.   Close
Leave a Comment
  • Try this to see what happens:

    PS>$input ="hello"



    Hmm.  Not a very good place to store things.

    It reminds me of this one:




    PowerShell is full of bit buckets:







    As opposed to:

    PS>New-Variable -Name y -Value $null -Option readonly




  • I used to frequently try to use $Host to represent a ComputerName.

    And $PID to represent the results from generic process ID's returned from Get-Process or Win32_Process

    They are not going to work  : )

  • @jrv

    This works though (assigning $_ and using it on the same line separated by semicolon):

    $_ = 5; $_

    This even works:

    $_ = 5; `


    This too:



    I don’t know if that’s guaranteed to work in the future or if that is just an accident. If it is not an accident, I would like to use that more often with scriptblocks that contain $_:

    $_=5; &$scriptblock

  • @imfrancisd  - UI believe what you have just demonstated was how to create an implied pipeline.  I am not sure that it is good for anything.

  • It's good if I want to make a function that takes a scriptblock, and I don't want the scriptblock to need to have a process block:

    Start-MyFunction {0 -lt $_ -and $_ -lt 10}