View Single Post
Old 02-08-2008   #3 (permalink)
Kirk Munro [MVP]


 
 

Re: What does the $() operator do?

Hi Kevin,

Technically it is called a subexpression. It basically instructs PowerShell
to evaluate it first and use the result of the subexpression wherever the
subexpression was located. This is very useful when building strings using
properties of objects. For example, suppose you needed to include the
department of a user as part of a string, and that your user was in a
variable called $user. You would use subexpressions to do this as follows:

"Department: $($user.department)"

Without the subexpression syntax the .department suffix would be treated as
a literal part of the string.

--
Kirk Munro [MVP]
Poshoholic
http://www.poshoholic.com

"jas" <james.seatter@xxxxxx> wrote in message
news:CB52EE09-F062-4E6A-8EF9-EA663DF36A36@xxxxxx
Quote:

> Kevin,
>
> Sometimes you need to evaluate an expression and then use the results to
> do something else.
>
> Classicly you would probably do
> $myvar = <some code that returns a value/object>
> if ($mayvar -eq "<somevalue>") { do something else }
>
> Using $() allows you to do this all in one line.
> if($(<some code that returns a value/object>) -eq "<somevalue>") { do
> something else }
>
> You will see this a lot in code as people force an expression to be
> evaluated, you may even see $($myvar) where $myvar is of a type that
> returns an unhelpful object but placing that inside another $() actually
> takes you to the value you want. I am sure smarter people can give more
> technical answers.
>
> James
>
>
> "Kevin Buchan" <kevin.buchan@xxxxxx[Pls Don't Spam]sanders.com> wrote in
> message newsmhoq3t1na8c4rg3gce6vgji0aoeiloqi2@xxxxxx
Quote:

>>I have googled and I've used get-help. I've even tried my own tests,
>> but I can't rell what the $() operator does.
>>
>> I've seen it in people's code and I think I can tell, from the
>> context, what it does, but I'm mistaken.
>>
>> #Example 1:
>> param(
>> [string] $wsdlLocation = $(throw "Please specify a WSDL
>> location"),
>> )
>>
>> #Example 2
>> $s = indent "<$($reader.Name) "
>>
>>
>> I was feeling like I was finally nearing the crest of the learning
>> curve, to where I can actually use PowerShell instead of simply
>> running other people's scripts, then I run into this. :-)
>>
>> Thanks!
>>
>> --
>> Kevin Buchan
>> kevin.bucahn@xxxxxx[nospam]sanders.com
>
My System SpecsSystem Spec