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!

Discuss this Blog Entry 1

on Jan 12, 2012
Don, I have just started reading your "powershell in a month of lunches" book. Our school system is the very first K12 system to go to Microsofts Office 365 online and powershell is going to be really useful for us so i am excited to learn more. I am really having a hard time with the "positional parameters" in chapter 3.

Please or Register to post comments.

What's PowerShell with a Purpose Blog?

Don Jones demystifies Windows PowerShell.

Blog Archive

Sponsored Introduction Continue on to (or wait seconds) ×