James Ko
James Ko

Reputation: 34599

How to pass arguments to an inline script in PowerShell?

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?

Upvotes: 0

Views: 5938

Answers (2)

Michael Sorens
Michael Sorens

Reputation: 36748

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.

Upvotes: 1

Χpẘ
Χpẘ

Reputation: 3451

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

Upvotes: 0

Related Questions