Glowie
Glowie

Reputation: 2309

Powershell - unable to print value of hash

I am writing a simple script to get more familiar with powershell.

This script reads input parameters into a hash

$states = @($args)

$states

write-host Color is $states.color

On the command-line, I set the following values

$shape = 'circle'; $color = 'pink'; $size = 'large'

I then invoke the program with the following command

.\shapes_n_colors.ps1  $shape $size $color

And, I get the following output:

circle
large
pink
Color is

I am unable to figure out why $states.color is blank. I was expecting the output "Color is pink"

I am following this artical, http://technet.microsoft.com/en-us/library/hh847780.aspx

Where am I going wrong???

Upvotes: 0

Views: 101

Answers (1)

BartekB
BartekB

Reputation: 8650

Not sure where to start...

First of all - you don't create hash at any point... @($args) doesn't do anything: $args is already an array, and @() is only useful to make sure that expression will produce an array... Hash literal is @{}.

Next: your script will have no clue what names you've used for variables passed to it. It will see three strings. I would suggest using param() to get named parameters (that by default are also positional, so calling script wouldn't change much):

param (
    $Shape,
    $Size,
    $Color
)

Write-Host Color is $Color

When you try it with your syntax, it will produce expected results. But wait, there's more. ;) With this you could run your script without a need to remember param order:

.\shapes_n_colors.ps1 -Color White -Shape Circle -Size Small

Not to mention that will complete this named parameters for you.

Upvotes: 1

Related Questions