Dec 212010
 

If you are writing a script that you want to (might) use again it can be really useful to use script parameters. PowerShell does some really cool things with parameters that many folks don’t know or realize you can do. This post covers some of those items.

To start us off let’s look at how to use a script parameter.

### Test-Param.ps1 ###
Param($Variable1 = "Hello", $Variable2 = "World")
"$Variable1 $Variable2"

If we save this script and run it we will get an output like this:

>>./Test-Param.ps1
>>Hello World

This simple case shows that our variables are being assigned to the default values. We can change these values by passing them to the script via the command line. These values are passed either in the order that they are sent, or statically assigned by using the variables name.

>>./Test-Param.ps1 "Goodbye"
>> Goodbye World

>> ./Test-Param.ps1 -Variable2 "Universe"
>> Hello Universe

>> ./Test-Param.ps1 "Universe" -Variable1 "Goodbye"
>> Goodbye Universe

As you can see, these are really pretty flexible. Another really cool part of params that you may have noticed by now if you are following along is that these variable names will use tab complete. So if you type “./test-param -” and then start hitting tab, you will cycle through all the names in the param block. If yo haven’t used a script in a long time, then you can quickly see what variables you might want to pass.

Now, sometimes you want to have the param feature, but you need to require the value. You can place some logic after the param block, but I like to just put code straight in there.

### Test-Param.ps1 ###
Param($Variable1 = Read-Host "Please input a value for Variable1",
      $Variable2 = Get-Content $Variable1
"$Variable1"
"$Variable2"

>> ./Test-Param.ps1
>> Please input a value for Variable1: c:ScriptTest.txt
>> c:ScriptTest.txt
>> Hello, World!

>> ./Test-Param.ps1 c:ScriptTest.txt
>> c:ScriptTest.txt
>> Hello, World!

>> ./Test-Param.ps1 c:ScriptTest.txt "Ignore my file"
>> c:ScriptTest.txt
>> Ignore my file

I think that just about covers it for this Quick Tip. Get started converting all your scripts to use a parameter block!

 Leave a Reply

(required)

(required)

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">