How to pass arguments to an Invoke-Expression, in PowerShell?
Asked Answered
R

2

6

I have the following (not working) PowerShell script:

$scriptPath = ((new-object net.webclient).DownloadString('https://gist.githubus
ercontent.com/AndrewSav/c4fb71ae1b379901ad90/raw/23f2d8d5fb8c9c50342ac431cc0360ce44465308/SO33205298')); $args = "`"aaa
bbb`"";  iex $scriptPath $args

So I'm:

  1. downloading the script to execute.
  2. settiping up my argument list to send into the script
  3. executing the script (for me, this is in the cli right now).

but it's erroring:

Invoke-Expression : A positional parameter cannot be found that accepts argument '"aaa bbb"'.
At line:1 char:209
+ ... 44465308/SO33205298')); $args = "`"aaa bbb`"";  iex $scriptPath $args
+                                                     ~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidArgument: (:) [Invoke-Expression], ParentContainsErrorRecordException
    + FullyQualifiedErrorId : PositionalParameterNotFound,Microsoft.PowerShell.Commands.InvokeExpressionCommand

How can I pass in the args to this script?

Note: this question references/spawned from this other SO question.

Reputable answered 19/10, 2015 at 3:40 Comment(0)
C
3

You should try something like this :

$scriptPath = ((new-object net.webclient).DownloadString('https://gist.githubusercontent.com/AndrewSav/c4fb71ae1b379901ad90/raw/23f2d8d5fb8c9c50342ac431cc0360ce44465308/SO33205298'))
Invoke-Command -ScriptBlock ([scriptblock]::Create($scriptPath)) -ArgumentList "coucou"

You have to create a ScriptBlock from source before invoking it.

Criminality answered 19/10, 2015 at 3:55 Comment(4)
> "You have to create a ScriptBlock from source before invoking it." - Not actually true. You can use IEX, II, and the & call operator to all invoke a string representation of Posh code.Pairs
@DaRKoN_and .. can i pass in named arguments? eg. -version 1.2.3.4 -source PewPew -foo whatever ?? <-- and those args are not in the same order as the param listed in the scriptReputable
@DaRKoN_ You are rigth II can invoke a script, but $Scriptpath is not a script path but the source of the script and I don't see how you start a script from source with Invoke-Item otherwise than saving the source to a file. The answer I give works here.Criminality
This is pretty awesome, I'm hoping I can passed named arguments through this as well.Reamer
B
0

As a pure one liner (you don't need to create the scriptblock separately) Also, using DownloadData in case the script has UTF-8 characters. Finally, Use an array for the ArgumentList to avoid issues with spaces in args.

powershell -nop -ExecutionPolicy Bypass -c "Invoke-Command -ScriptBlock ([scriptblock]::Create([System.Text.Encoding]::UTF8.GetString((New-Object Net.WebClient).DownloadData('https://server.com/upload/script.ps1')))) -ArgumentList @('somearg','someotherarg')"
Baltazar answered 16/2, 2023 at 21:36 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.