Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to evaluate PowerShell script inputed from stdin

I want to evaluate the content from StdIn in PowerShell, like this:

echo "echo 12;" | powershell -noprofile -noninteractive -command "$input | iex"

Output:

echo 12;

Unfortunately, $input is not a String, but a System.Management.Automation.Internal.ObjectReader, which make iex not working as expected... since this one is working correctly:

powershell -noprofile -noninteractive -command "$command = \"echo 12;\"; $command | iex"

Output:

12
like image 579
sandvige Avatar asked Dec 14 '12 09:12

sandvige


People also ask

How do you pass input parameters in PowerShell script?

You can pass the parameters in the PowerShell function and to catch those parameters, you need to use the arguments. Generally, when you use variables outside the function, you really don't need to pass the argument because the variable is itself a Public and can be accessible inside the function.

How do I get user input in PowerShell?

Use the Read-Host to Prompt for User Input in PowerShell The Read-Host cmdlet prompts user input and reads a line of input from the console. The Read-Host can accept only 1022 characters as input from a user. The -Prompt parameter is used to specify a text to provide the information about what to input.

What is param () in PowerShell?

The PowerShell parameter is a fundamental component of any script. A parameter is a way that developers enable script users to provide input at runtime. If a PowerShell script's behavior needs to change in some way, a parameter provides an opportunity to do so without changing the underlying code.

Why we use $_ in PowerShell?

The $_ is a variable or also referred to as an operator in PowerShell that is used to retrieve only specific values from the field. It is piped with various cmdlets and used in the “Where” , “Where-Object“, and “ForEach-Object” clauses of the PowerShell.


Video Answer


2 Answers

The following would work:

Use a scriptblock:

echo "echo 12;" | powershell -noprofile -noninteractive -command { $input | iex }

Or use single quotes to avoid the string interpolation:

 echo "echo 12;" | powershell -noprofile -noninteractive -command '$input | iex'

so the $input variable isn't expanded, and the string '$input' is passed to iex.

Both of these give me "12".

like image 184
Marcus Avatar answered Oct 19 '22 11:10

Marcus


Just use - as a source file "name":

echo "echo 12;" | powershell -noprofile -noninteractive -
like image 42
Martin Prikryl Avatar answered Oct 19 '22 13:10

Martin Prikryl