Pure.Krome
Pure.Krome

Reputation: 86957

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

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.

Upvotes: 6

Views: 9955

Answers (2)

NitrusCS
NitrusCS

Reputation: 753

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')"

Upvotes: 0

JPBlanc
JPBlanc

Reputation: 72630

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.

Upvotes: 3

Related Questions