• This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn more.

Invoke-expression vs &

L

Leo Tohill

#1
What's the difference?

For example,

$t='notepad c:\temp\x.txt'
&$t # this fails
invoke-expression $t #this works

More generally, I'm still puzzled about when the interpretation of strings
occurs.

tia
 

My Computer

S

Shay Levi

#2
Check out Keith's article, Effective PowerShell Item 10: Understanding PowerShell
Parsing Modes
http://keithhill.spaces.live.com/Blog/cns!5A8D2641E0963A97!6058.entry


-----
Shay Levi
$cript Fanatic
http://scriptolog.blogspot.com
Hebrew weblog: http://blogs.microsoft.co.il/blogs/scriptfanatic



> What's the difference?
>
> For example,
>
> $t='notepad c:\temp\x.txt'
> &$t # this fails
> invoke-expression $t #this works
> More generally, I'm still puzzled about when the interpretation of
> strings occurs.
>
> tia
>
 

My Computer

K

Keith Hill [MVP]

#3
"Shay Levi" <no@xxxxxx> wrote in message
news:8766a944fdd88ca000612134012@xxxxxx

> Check out Keith's article, Effective PowerShell Item 10: Understanding
> PowerShell Parsing Modes
> http://keithhill.spaces.live.com/Blog/cns!5A8D2641E0963A97!6058.entry
Thanks. :-)

>> $t='notepad c:\temp\x.txt'
>> &$t # this fails
In this case, the call operator (&) expects $t to be the *command* to
execute and not an entire command line (with args, etc). IOW, while
'notepad' is a valid command, 'notepad c:\temp\x.txt' isn't. This would
work:

$t = 'notepad'
&$t c:\temp\x.txt

>> invoke-expression $t #this works
Invoke-Expression executes the whole string as if it were type in at the
command line.

--
Keith
 

My Computer

K

Karl Prosser[MVP]

#4
yep & runs a command, invoke-expression first parses a string of text,
and runs that, and thus is vulnerable to "powershell injection attacks".

if you specify a preparsed scriptblock you can run that with the &, and
unless your command is generated dynamically as a string, this is
preferable over invoke-expression..


$t={notepad c:\temp\x.txt}
&$t # this fails



or

$mypath = '.....something that works';
$t = {notepad $mypath}

&$t
 

My Computer

#5
Probably simpler to use scriptblocks (curly brackets) with &, rather than
strings, as Karl suggests. You don't have to be so concerned about what
constitutes a command, and what constitues an argument, which also leads to
simpler syntax eg with a string


& 'notepad' c:\temp\x.txt #An executable
& 'Get-Process' power* #A cmdlet
function sayhello {"hi there!"} ; & "sayhello" #A function
set-alias abc sayhello ; & "abc" #An alias

whereas with a scriptblock, you can just use

& {notepad c:\temp\x.txt } #Assuming the file exists
& {Get-Process power*}

etc

--
Jon
 

My Computer

Users Who Are Viewing This Thread (Users: 1, Guests: 0)