Reputation: 110
If I do the following I get what is supposed to do (get the content from a file with curl and then execute the content as powershell code).
$Uri = "some-arbitrary-uri.com/file.txt"
Invoke-Expression (Invoke-WebRequest -Uri $Uri).Content
But when putting it inside a function it stops working.
function Invoke-FileContentExpression($Uri)
{
Invoke-Expression (Invoke-WebRequest -Uri $Uri).Content
}
Invoke-FileContentExpression -Uri $Uri
Upvotes: 0
Views: 537
Reputation: 8878
As Theo commented, Invoke-Expression
can be dangerous to run. The issue you are facing has nothing to do with Invoke-Expression
, it has to do with scopes. Functions execute in their own scope. See the example below.
# variable is populated in the current scope
$var = 'hello world'
Write-Host Var contains $var # Var contains hello world
# var is populated in the functions scope and is gone after the function ends
Function Write-HelloWorld {
$var = 'HELLO WORLD'
}
Write-Host Var contains $var # Var contains hello world
So the Invoke-Expression
is doing what you told it in the function scope and is gone when the function ends. If you want to pull that up to your scope, just dot source it.
function Invoke-FileContentExpression($Uri)
{
Invoke-Expression (Invoke-WebRequest -Uri $Uri).Content
}
. Invoke-FileContentExpression -Uri $Uri
Upvotes: 4