Mark
Mark

Reputation: 11750

What does this PowerShell snippet mean (syntax parsing help!)

I have the following snippet of PowerShell script in my profile:

. (join-path (split-path (& { $myInvocation.ScriptName })) "export-errors.ps1")

Now, I understand that this causes the script export-errors.ps1 that exists in the same directory as my profile script to be executed. My question is, why?

I don't understand why the & { xxx } construct is different that just xxx in this case. I've attempted to use this similar construct:

$lame = join-path (split-path $myinvocation.mycommand.definition) "_lame\lame.exe"

This doesn't work, however. I get errors about providers not existing, and I don't really understand why.

Why does the first construct work, and the second one doesn't?

UPDATE

It's become clear to me that I was chasing the wrong bug. Indeed, both of the constructs work, under certain conditions. The condition under which I was running the second construct, however, is one under which NEITHER works. I'll post a separate question on that.

Keith is almost certainly correct when he says the first construct is an attempt to work around certain oddities. It was a copy-paste thing from a LONG time ago.

Upvotes: 0

Views: 308

Answers (1)

Keith Hill
Keith Hill

Reputation: 202072

That syntax is probably over the top for dot sourcing in your profile. The following should be sufficient in the context of your profile.ps1 script:

. (join-path (split-path $MyInvocation.MyCommand.Path) export-errors.ps1)

Of course if you're dot sourcing more than one file you might want to go this route:

$ScriptPath = $MyInvocation.MyCommand.Path
$ScriptDir = Split-Path $ScriptPath -Parent
. $ScriptDir\lib.ps1

I believe your original approach attempts to work around a problem I describe in this blog post.

Upvotes: 2

Related Questions