tags:

views:

46

answers:

2

I'm confused about the difference between these two things:

$env:path

And

function path {$env:path}
path

Both return strings, according to get-member. Yet -match does not work the same on both.

If I use -match on $env:path, it works as I'd expect, returning true/false. But if I use -match on path (the new function) then it always returns the path, ignoring the -match.

I'm confused because both return strings and therefore ought to work the same. Does the function need to do something special to get the same result?

+1  A: 

Have you tried something like

$(path) -match

I'm on Ubuntu here, so I can't verify. The $() causes the expression to be evaluated, and then I believe the -match should operate on the returned string

The reason I suggest this is that is seems to me that if you don't put the function call in the expression evaluator, the -match might be treated as a parameter to the path function, and ignored since the path function doesn't know about -match.

David Gladfelter
Hey Dave, welcome to SO! :-)
Keith Hill
Thanks, glad to be here.
David Gladfelter
+4  A: 

David is right. The difference is that -match is being treated as a parameter to the path function. So,

$(path) -match "foo"

or

(path) -match "foo" 

works equally well. The former is a subexpression, the latter a nested pipeline (usually same effect in cases like this, but there are subtle differences.)

Verify:

ps> function path {$env:path; write-host "parameters: $args"}
ps> path -match "foo"
(env:path expanded)
parameters: -match foo

-Oisin

x0n
Hi Oisin, do you know Keith Hill from your Powershell work? I used to work with him until I got laid off from Agilent last year.
David Gladfelter
Yeah, I do David. I work with him on a few OSS projects (like PSCX) and I'll be seeing him in person in Redmond, WA, in a few weeks time.
x0n
Great answer, thank you. The $() and () continue to trip me up as I learn.
Scott Bilas
Btw what is the subtle difference between a subexpression and a nested pipeline?
Scott Bilas
Keywords (as opposed to commands) cannot appear as the first item in a pipeline, but they can in subexpressions. An example: (if ($true) { "ok" }) => error but: $(if ($true) { "ok" }) => ok
x0n
also, subexpression $(@(1)) is a single int, but (@(1)) is an object[] array.
x0n
Glad to hear he managed to pull together a trip to Redmond again. Agilent has been reticent to pay for his trips in the past.
David Gladfelter