Skip navigation

Making PowerShell Params

I've been answering questions over at http://bitly/AskDon for a few months now, and I've been helping more than a few folks unravel some grave misunderstandings. At first, I thought, "where in the world did they get this stuff," and then I thought, "the Internet," and it all made sense! When you're trying to get a job done by piecing together things on the Internet, you run into several problems. First, not everyone on the Internet has actually got a clue. Second, sometimes they're not clear why they did a certain thing, and you're not clear what it does, so you try it sorta and it kinda doesn't really work.


PowerShell parameters are one of the things that have come up several times in that regard. I'll see…


Param (
  [Parameter(Position=0)[string]$computername,
  [Parameter(Position=1)[string]$filepath
)



Stuff like that. Which isn't wrong, but it's… misinformed. And actually, in this case, the syntax actually is wrong. So let's start over.


Param(
  [string]$computerName,
  [string]$filePath
)



That's all you need to create a -computerName and -filePath parameter for your script. They're automatically positional, meaning you can run the script with "./script SERVER1 c:\files" passing the parameter values in the same order they're defined, without actually typing the parameter names. You don't need the fancy [Parameter()] decorator - which has opening and closing square brackets, by the way. 


If you want to get fancier, you should go all the way and provide the full fancy syntax:


[CmdletBinding()]
Param (
  [Parameter(Mandatory=$True,Position=0)]
  [string]$computername,
  
  [Parameter(Position=1)]
  [string]$filepath
)



And do a friend a favor and format it nicely, like this, k? I've given each parameter a [Parameter()] decorator so that I could specify position number and make one of them mandatory; you don't have to include the decorator on any parameters that don't need something defined. For each, I put the decorator on a line, then the parameter, and I put a blank line between parameters. Folks, white space is 100% free of charge, so use it to make your scripts more readable.


Parameters are a great idea. Declare them properly, use them effectively, and type them neatly!
Hide comments

Comments

  • Allowed HTML tags: <em> <strong> <blockquote> <br> <p>

Plain text

  • No HTML tags allowed.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.
Publish