0

I'm new to PowerShell scripting. I was wondering if there was a way to invoke a script inline without creating a new .ps1 file and pass arguments to it, e.g.

powershell -command "echo `$args[0]" 123 456

I want echo $args[0] to be the script and 123 456 to be the arguments, but PowerShell seems to interpret 123 456 as part of the script (as if I'd wrote "echo `$args[0] 123 456") and prints

123
456

Is it possible to work around this without creating a new PowerShell script on disk?

2
  • 2
    From within PowerShell you could do powershell.exe -command {echo $args[0]} -args 123,456 Commented Nov 22, 2015 at 5:09
  • What's provoking the question? Commented Nov 22, 2015 at 5:23

2 Answers 2

1

So far you have seen a couple answers and comments showing you how to do just what you asked for. But I have to echo @BillStewart's comment: what is your true purpose?

If it is to be able to execute some arbitrary PowerShell that you have in a string, you could certainly invoke powershell.exe, as you have seen in a couple answers and comments. However, if you do that be sure to include the -noprofile parameter for improved efficiency. And for even more efficiency, you could use Invoke-Command without having to spin up a whole separate PowerShell environment, e.g.

Invoke-Command -ScriptBlock ([Scriptblock]::Create('echo $args[0]')) -arg 123, 456

If, on the other hand, you want to execute a chunk of PowerShell (not within a string but just separate in your script for whatever reason), you can simplify to this:

Invoke-Command -ScriptBlock {echo $args[0]} -arg 123, 456

Whenever you have the choice though, avoid manipulating strings as executable code (in any language)! The oft-used way to do that in Powershell is with Invoke-Expression, which I mention only to point you to the enlightening article Invoke-Expression considered harmful.

Sign up to request clarification or add additional context in comments.

Comments

0

This does what I think you want:

powershell -command "& {write-host `$args[0] - `$args[1] - `$args[2]}" 123 456 789

Each element of the $args array is a different parameter so to access three parameters you need $args[0], $args[1], and $args[2].

You could also use the param statement and get named parameters:

powershell -command "& {param(`$x,`$y); write-host `$x - `$y}" -x 123 -y 456

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.